0

I have a TextInputEditText inside a TextInputLayout. I want to change the TextInputLayout's background based on whether the EditText has focus or not. I can easily accomplish that by observing the edittext's focus from the activity and then update the background accordingly. But it seems such a waste to update the element from the activity if I'm already using Data Binding. Is there a way to reference the TextInputLayout's background from the focus change callback inside the EditText?

<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>
BVtp
  • 2,308
  • 2
  • 29
  • 68

1 Answers1

0

Yes you can, just keep in mind that you have to account for when you lose focus. It could be due to the back button, switching input fields or hitting enter on the keyboard. Since you do not know what the user will do you can account for that as discussed here based on your use case..

In your layout

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

A lambda is used to call the appropriate background based on the viewmodel data while onClick determines if it is in focus.

In you viewmodel (Kotlin)

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

fun setFocus(value: Boolean){
       hasFocus.value = value
}
cndjonno
  • 76
  • 1
  • 6