Change TextInputLayout accent color programmatically

后端 未结 2 1795
醉酒成梦
醉酒成梦 2020-12-17 15:27

I\'ve got a simple TextInputLayout containing an EditText View.

Now I wonder how to change the accent color (underline, hintTextColor when highlighted) programmatica

相关标签:
2条回答
  • 2020-12-17 16:03

    You can try this for the text,

    InputTextLayout.getEditText().setHighlightColor(yourColor);
    InputTextLayout.getEditText().setHintTextColor(yourColor);
    

    and this for the line at the bottom of the EditText

    Drawable background = InputTextLayout.getEditText().getBackground();
    DrawableCompat.setTint(background, yourColor);
    InputTextLayout.getEditText().setBackground(background);
    

    Hope it works!

    0 讨论(0)
  • 2020-12-17 16:09

    IMHO InputTextLayout can not change label color programmatically, because it is set by style. I examined source code of InputTextLayout and wrote this hack helper method which create access to private color member:

    public static void setInputTextLayoutColor(EditText editText, @ColorInt int color) {
        TextInputLayout til = (TextInputLayout) editText.getParent();
        try {
            Field fDefaultTextColor = TextInputLayout.class.getDeclaredField("mDefaultTextColor");
            fDefaultTextColor.setAccessible(true);
            fDefaultTextColor.set(til, new ColorStateList(new int[][]{{0}}, new int[]{ color }));
    
            Field fFocusedTextColor = TextInputLayout.class.getDeclaredField("mFocusedTextColor");
            fFocusedTextColor.setAccessible(true);
            fFocusedTextColor.set(til, new ColorStateList(new int[][]{{0}}, new int[]{ color }));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    mFocusedTextColor is used for set internal CollapsingTextHelper.mCollapsedTextColor which sets color of label.

    0 讨论(0)
提交回复
热议问题