我将数据绑定(bind)与 TextInputLayout/TextInputEditText 组合一起使用,如 xml 中所示。
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/lastname_input_layout"
style="@style/TextInputLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:endIconMode="clear_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/firstname_input_layout"
app:visible="@{viewModel.showFields}">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/lastname_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/lastname"
android:inputType="textCapWords"
android:text="@={viewModel.lastName}"
android:textAppearance="@style/TextAppearance.Input" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/email_input_layout"
style="@style/TextInputLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:endIconMode="clear_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/lastname_input_layout"
app:visible="@{viewModel.showFields}">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/email_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@{viewModel.watchMediaTextHint}"
android:inputType="@{viewModel.watchMediaInputType}"
android:text="@={viewModel.mediaText}"
android:textAppearance="@style/TextAppearance.Input" />
</com.google.android.material.textfield.TextInputLayout>
如您所见,这两个字段在理论上是相同的,唯一的区别是其中一个字段具有
hint
用字符串资源给出的文本,另一个用数据绑定(bind)给出。两者具有相同的样式,文本外观等,但是,TextInputEditText
上的提示使用数据绑定(bind)有不同的颜色。此外,当 View 获得焦点时,标签不会像第一个字段那样动画。使用字符串资源设置提示可以使这种行为恢复正常,关于为什么会发生这种异常的任何想法?我宁愿通过数据绑定(bind)而不是编程解决方案来解决这个问题。
谢谢。
最佳答案
hint
如果属性设置为 <TextInputLayout>
,则该属性仅与数据绑定(bind)结合使用。而不是 <TextInputEditText>
.<TextInputEditText>
小号 hint
属性仅在膨胀期间应用一次,因此在与数据绑定(bind)结合使用时不会更新/应用。
请注意@Mike M. 的评论。我将其转换为答案,以便其他人更容易找到。
关于android - 使用数据绑定(bind)时 TextInputLayout 提示不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61466930/