How to set different colors of TextInputLayout's boxBackground?

Viewed 457

I have a simple input field using the TextInputLayout. I can set the box background color with

setBoxBackgroundColorResource(R.color.mycolor)

But now I would like to have different colors depending on state. mycolor_activated for activated state, and mycolor_default for detault state. Creating a color state list and setting it as the resource does not work, it ignores the activated state:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:color="#FFF" />
    <item android:color="#000" />
</selector>
setBoxBackgroundColorResource(R.color.myselector)

Is there a way to do this? I don't have problems setting color state list for stroke for example. Please note that I also need to set the TextInputLayout's properties programmatically.

1 Answers

You can use the method setBoxBackgroundColorStateList.

textInputLayout.setBoxBackgroundColorStateList(
         ContextCompat.getColorStateList(this,R.color.my_selector));

Note: this method requires at least the version 1.2.0-beta01

It is the default selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:alpha="..." android:color="...." android:state_hovered="true"/>
  <item android:alpha="..." android:color="..." android:state_focused="true"/>
  <item android:alpha="..." android:color="..." android:state_enabled="false"/>
  <item android:alpha="..." android:color="..."/>
</selector>
Related