为什么Android会更改具有相同id的EditTexts的值? [英] Why does Android change the value of EditTexts with same id?

查看:15
本文介绍了为什么Android会更改具有相同id的EditTexts的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 LinearLayout 的片段,其中根据某些业务逻辑对不同的项目进行膨胀.在这些项目中包含一个 EditText.当我有多个具有不同内容的项目并且我分离/附加片段时,所有 EditTexts 都会以某种方式获得所有相同的文本.仅当 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 上的问题p>

I've created a minimalistic example to demonstrate the problem at https://github.com/rodja/EditTextValueProblem

推荐答案

只需在 EditTexts Layout 定义中设置 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 作为存储其状态的键,因此它依赖于整个树中的唯一性.什么鬼?

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?

更新

我已将 ListView 添加到 GitHub 上的示例 中,该示例演示了 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆