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

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

问题描述

我有一个包含 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 作为键来存储它的状态,因此它依赖于整个树中的唯一性.跆拳道?

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屋!

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