android - 基于焦点的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>
解决方案
是的,你可以,但请记住,当你失去焦点时,你必须考虑到这一点。这可能是由于后退按钮、切换输入字段或在键盘上按 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
}
推荐阅读
- sql-server - 将 CSV 文件数据导入 SQL Server
- php - 如何在浏览器上实时打印传入的 webhook 数据?
- javascript - React-native-google-signin - 无法读取未定义的属性“编号”
- c# - 如何查询 Win32_Printer 以获取已安装的远程打印机?(无效查询)
- php - PHP Laravel - 如何通过名称模板选择 mysql 表名
- angular - Angular Route.navigate 在新选项卡中
- android - OkHttp 请求错误链接时崩溃
- facebook - 即使没有 Facebook 登录,Facebook 应用程序分析是否允许我跟踪移动应用程序用户洞察?
- javascript - 在 MVC 5 中,如何将表对象数据作为列表传递给控制器视图模型?
- macos - Javafx mac终端外部进程