Why does Android change the value of EditTexts with same id?

杀马特。学长 韩版系。学妹 提交于 2019-11-30 04:57:00

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!