Android为什么要更改具有相同ID的EditTexts的值? [英] Why does Android change the value of EditTexts with same id?
问题描述
我有一个包含LinearLayout的Fragment,根据某些业务逻辑,其中会膨胀不同的项目.这些项目中的一个包含一个EditText.当我有多个具有不同内容的项目并且我分离/附加了片段时,所有EditText都会以某种方式获得所有相同的文本.仅当EditText在布局文件中具有ID时,这种情况才会发生.
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.
为什么会这样?除了删除ID之外,还有其他方法可以防止这种情况吗?我想在充气物品上使用findViewById
来访问视图,而不是容易出错的getChildAt
.
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
.
我创建了一个简约的示例,以在 https://github.com/rodja/EditTextValueProblem 上演示该问题 >
I've created a minimalistic example to demonstrate the problem at https://github.com/rodja/EditTextValueProblem
推荐答案
只需在EditTexts布局定义中设置android:saveEnabled="false"
即可对其进行修复.当然,您需要确保自己保存/恢复了内容.因此,这是一种非直觉的解决方法,但它适用于我的情况.尽管如此,整个事情看起来像是一个Android错误:
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:
Android布局系统的一个不错的功能是
A nice feature of the Android layout system is that
ID在整个树中不必唯一[...]
An ID need not be unique throughout the entire tree [...]
如 Android文档所述.这使得代码和布局的重用变得更加简单,并且被开发人员大量使用.我认为视图的保存/恢复实例状态实现使用视图的ID作为存储状态的键,因此它依赖于整个树中的唯一性. WTF?
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?
更新
我已经在 GitHub上的示例中添加了ListView
,这表明ListView
几乎可以肯定地使用了类似的解决方法以防止EditTexts遇到此问题.可以看出,在ListView内输入EditText的文本不会自动恢复.
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.
这篇关于Android为什么要更改具有相同ID的EditTexts的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!