简体   繁体   English

更改 TextInputLayout 轮廓颜色(或如何覆盖主题/样式中的颜色)

[英]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.之前我问过如何自定义 TextInputLayout 的轮廓颜色。 You can check the question in this LINK .您可以在此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.这有效,但会更改应用程序中所有 TextInputLayout 的线条颜色。 How can I apply different colors to different TextInputLayouts within the same app?如何在同一个应用程序中将不同的颜色应用于不同的 TextInputLayouts?

Thanks谢谢

Well you can always use ye olde reflection until Google figures out how we can access simple and rather basic stuff like this.好吧,在 Google 弄清楚我们如何访问像这样简单且相当基本的东西之前,您总是可以使用古老的反射。 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. TextInputLayout 类中的字段称为 defaultStrokeColor,因此如果您将其设置为可访问并更改值,那么在现实世界中它也应该更改。

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.您可以在 res/color 下创建一个 xml 文件,并像这样设置选择器。

<?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"和 TextInputLayout app:boxStrokeColor="@color/xml_just_create"设置属性app:boxStrokeColor="@color/xml_just_create"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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