10

I'm trying to use these material text fields with the box outline style. I see that there's a property called boxStrokeColor which lets me set the stroke only when the text field is highlighted when it's not highlighted it seems to pull that color from the global theme's colorPrimary value.

In our app the user can set their own background color for certain views and I'd like to change the stroke color of the text field to a suitable contrasting color.

Is there any clean way to set the unhighlighted box stroke color programmatically?

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
TylerJames
  • 941
  • 8
  • 27
  • 1
    Did you find a solution for this? Wondering the same thing. So sad how material components always seem very nicely executed but when you start using them you notice they always seem to lack something... – Ruben2112 Feb 07 '19 at 14:15
  • 1
    Unfortunately not yet. I appreciate the work that's going into these libs but it does seem like a "breadth first" approach where some of the components are lacking obvious configuration options. Personally I hate it when a component *relies* on the global theme and can't be tweaked programmatically. – TylerJames Feb 07 '19 at 19:25

2 Answers2

8

You can use the setBoxStrokeColorStateList method. Something like:

textInputLayout.setBoxStrokeColorStateList(AppCompatResources.getColorStateList(this,R.color.text_input_layout_stroke_color));

It works with a selector as:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="?attr/colorPrimary" android:state_focused="true"/>
  <item android:alpha="0.87" android:color="?attr/colorOnSurface" android:state_hovered="true"/>
  <item android:alpha="0.12" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
  <item android:alpha="0.38" android:color="?attr/colorOnSurface"/>
</selector>
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
1

After a lot of experimenting here is what I have found. This is a correct format

val colorState = ColorStateList(
        arrayOf(intArrayOf(android.R.attr.state_active),
            intArrayOf( android.R.attr.state_focused),
            intArrayOf( -android.R.attr.state_focused),
            intArrayOf( android.R.attr.state_hovered),
            intArrayOf( android.R.attr.state_enabled),
            intArrayOf(- android.R.attr.state_enabled)),
        intArrayOf(Color.parseColor(activeColor), 
            Color.parseColor(focusedColor),     
            Color.parseColor(unfocusedcolor), 
            Color.parseColor(hoveredColor),
            Color.parseColor(enabledColor),
            Color.parseColor(disabledColor))
    )

    inputLayout.setBoxStrokeColorStateList(colorState)
nayan dhabarde
  • 1,734
  • 1
  • 19
  • 38