Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
871 views
in Technique[技术] by (71.8m points)

android - Programmatically set TextInputLayout Hint Text Color and Floating Label Color

I use a TextInputLayout, I would want to programmatically set the hint text color and the floating label color if the input field is mandatory. Before moving to TextInputLayout I used to set the hint text color programmatically using the following

textField.setHintTextColor(Color.RED);

Can someone guide me on how to set the hint text color and the floating label color programmatically for a TextInputLayout.

In the screenshot attached i would want the hint text Address 1 to be in red when not focused and the on focus the floating label Address 1 should be in red.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I changed focused color with reflection. Here's the snippet it may help someone.

private void setUpperHintColor(int color) {
    try {
        Field field = textInputLayout.getClass().getDeclaredField("mFocusedTextColor");
        field.setAccessible(true);
        int[][] states = new int[][]{
                new int[]{}
        };
        int[] colors = new int[]{
                color
        };
        ColorStateList myList = new ColorStateList(states, colors);
        field.set(textInputLayout, myList);

        Method method = textInputLayout.getClass().getDeclaredMethod("updateLabelState", boolean.class);
        method.setAccessible(true);
        method.invoke(textInputLayout, true);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

EDIT 2018-08-01:

If you are using design library v28.0.0 and later, fields had changed from mDefaultTextColorto defaultHintTextColor and from mFocusedTextColor to focusedTextColor.

Check decompiled class for other fields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...