I have a Fragment containing a LinearLayout where different items are inflated depending on some business logic. On of these items contains an EditText. When I have multiple of these items with different content and I detach/attach the fragment, all EditTexts somehow get all the same text. This only happens as long as the the EditText has an id in the layout file.
Why does that happen? Is there any other way to prevent this except removing the id? I would like to use findViewById
on my inflated items to access the views instead of error prone getChildAt
.
I've created a minimalistic example to demonstrate the problem at https://github.com/rodja/EditTextValueProblem
There is a different possibility, just change the id of the edit text, for example,
Or if it is a EditText inside some custom Layout:
In this way all EditTexts will have a different id and the text will be restored correctly.
It can simply be fixed by setting
android:saveEnabled="false"
in the EditTexts Layout definition. Of course you need to make sure that the content is saved/restored yourself. So this is an non-intuitive work around -- but it works for my case. None the less the entire thing looks like an Android bug:A nice feature of the Android layout system is that
as stated in the Android documentation. This makes code and layout reuse much simpler and is heavily used by developers. I think the save/restore instance state implementation for views uses the view's ID as the key to store it's state, hence it relies on uniqueness in the entire tree. WTF?
Update
I have added a
ListView
to the example at GitHub which demonstrates that theListView
almost certainly uses a similar workaround to prevent EditTexts to run into this problem. As can be seen, text which is entered into an EditText inside a ListView is not automatically restored.