view – Why does Android change the value of EditTexts with same id?-ThrowExceptions

Exception or error:

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

How to solve:

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

An ID need not be unique throughout the entire tree […]

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 the ListView 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.

###

There is a different possibility, just change the id of the edit text, for example,

mEditText.setId((parentView.getId()+editTextPosition+someFinalNumber));

Or if it is a EditText inside some custom Layout:

mEditText.setId((this.getId()+someFinalNumber));

In this way all EditTexts will have a different id and the text will be restored correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *