問題描述
我有一個包含 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的值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!