【问题标题】:DataBinding background drawable update based on focus基于焦点的 DataBinding 背景可绘制更新
【发布时间】:2019-08-07 11:28:00
【问题描述】:

我在 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>

【问题讨论】:

    标签: android kotlin layout data-binding


    【解决方案1】:

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

    在您的布局中

    <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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多