简体   繁体   中英

Change the TextInputLayout outline color (Or how to override a color in a theme/style)

Previously I asked how to customize the outline color of a TextInputLayout. You can check the question in this LINK .

Declaring this color in my app:

<color name="mtrl_textinput_default_box_stroke_color" tools:override="true">#fff</color>

This works, but changes the line color of all the TextInputLayout in the app. How can I apply different colors to different TextInputLayouts within the same app?

Thanks

Well you can always use ye olde reflection until Google figures out how we can access simple and rather basic stuff like this. The field in the TextInputLayout class is called defaultStrokeColor, so if you set it accessible and change the value then in the real world it should also change.

try {
    Field field = TextInputLayout.class.getDeclaredField("defaultStrokeColor");
    field.setAccessible(true);
    field.set(commentInputLayout,
        ContextCompat.getColor(itemView.getContext(), R.color.app_middleweight));
}
catch (NoSuchFieldException | IllegalAccessException e) {
    Log.w("TAG", "Failed to change box color, item might look wrong");
}

You can create a xml file under res/color and setup selector like this.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="@color/color_id_when_focus" 
  android:state_focused="true" />
  <item android:color="@color/default_color_id" />
</selector>

And setup attribute for TextInputLayout app:boxStrokeColor="@color/xml_just_create"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM