Android - TextInputLayout hint text color, error color

224 views Asked by At

There are some questions and workarounds about this topic. But they are out-dated solution. I use support:design:28.0.0.

Firstly, I set hint text color using setDefaultHintTextColor method. Below code works as expected.

    final int[][] states = new int[][] {
            new int[] { android.R.attr.state_focused},
            new int[] {}
    };

    final TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);
    textInputLayout.setErrorEnabled(true);

    final ColorStateList hintStateList = new ColorStateList(states, new int[] {Color.BLACK, Color.GREEN});
    textInputLayout.setDefaultHintTextColor(hintStateList);

    textInputLayout.setHintEnabled(true);
    textInputLayout.setHint("My hint");

Focused state: enter image description here

Unfocused state: enter image description here

I set an error message textInputLayout.setError("My error"); It breaks my hint color setting. Because this is default behaviour of support:design:28.0.0, but not support:design:27.+.

enter image description here

Old-style reflection doesn't solve this issue.

private void tryReflection(int color, TextInputLayout textInputLayout) {
    try {
        Field field = textInputLayout.getClass().getDeclaredField("focusedTextColor");
        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();
    }
}

It doesn't work when you set error message or error message color.

0

There are 0 answers