首页 > 解决方案 > 设备旋转后双向 DataBinding 出错

问题描述

我使用带有LiveData的 Android DataBinding 库(双向)(绑定语法@={})

为了复用 UI,我在设计布局文件时大量使用了include 布局机制。实际上,我在构建表单布局时多次包含同一个布局文件。

一切顺利,直到设备旋转。设备旋转后,所有字段(editText)都得到与最后一行相同的值(如下图所示)。

旋转后重新创建活动时会出现问题,因此我可以通过设置活动的 android:configChanges 来防止这种情况。但我很好奇这个问题的根源以及如何解决它。.

您可以在下面找到源代码的主要部分或完整的源代码。提前致谢。

在此处输入图像描述


源代码

在此处输入图像描述

标签: androidandroid-databindingandroid-architecture-componentsandroidxtwo-way-binding

解决方案


To one who may concern about this problem, the reason seems to be related to the ID of editText in form row layout (Layout for a row (1 TextView & 1 EditText)), i.e. android:id="@+id/editTextID" in this case.

Three rows for first name, last name and password created by using the same row layout so editTexts for these fields haves the same ids.

After the rotation, the frameworks could notify the changes in edit text of the last row (password) but the two first rows also receive these updates. That probably causes the problem.

To resolve it, simple remove android:id="@+id/editTextID" in the row layout. There is nothing related to ViewModel or its lifeCycle.


推荐阅读