首页 > 解决方案 > 基于焦点的DataBinding后台drawable更新

问题描述

我在 TextInputLayout 中有一个 TextInputEditText。我想根据 EditText 是否有焦点来更改 TextInputLayout 的背景。我可以通过从活动中观察编辑文本的焦点来轻松实现这一点,然后相应地更新背景。但是如果我已经在使用数据绑定,那么从活动中更新元素似乎是一种浪费。有没有办法从 EditText 内的焦点更改回调中引用 TextInputLayout 的背景?

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/input_field_unselected_background">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:inputType="text"
        android:hint="@string/hint_placeholder"
        android:background="@android:color/transparent"/>
</com.google.android.material.textfield.TextInputLayout>

标签: androidkotlinlayoutdata-binding

解决方案


是的,你可以,但请记住,当你失去焦点时,你必须考虑到这一点。这可能是由于后退按钮、切换输入字段或在键盘上按 Enter 所致。由于您不知道用户会做什么,因此您可以根据您的用例在此处进行说明。

在您的布局中

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@{viewModel.hasFocus ? @drawable/background_focused : @drawable/background_unfocused}">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:inputType="text"
        android:hint="@string/hint_placeholder"
        android:background="@android:color/transparent"
        android:onClick="@{() -> viewModel.setFocus(true)}"/>
</com.google.android.material.textfield.TextInputLayout>

lambda 用于根据 viewmodel 数据调用适当的背景,而 onClick 确定它是否处于焦点。

在您的视图模型中(Kotlin)

val hasFocus = MutableLiveData<Boolean>().apply{postValue(false)}

fun setFocus(value: Boolean){
       hasFocus.value = value
}

推荐阅读