以编程方式设置TextInputLayout提示文本颜色和浮动标签颜色 [英] Programmatically set TextInputLayout Hint Text Color and Floating Label Color

查看:87
本文介绍了以编程方式设置TextInputLayout提示文本颜色和浮动标签颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用TextInputLayout,如果必须输入字段,我想以编程方式设置提示文本颜色和浮动标签颜色.移至TextInputLayout之前,我曾经使用以下程序通过编程方式设置提示文本的颜色

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);

有人可以指导我如何以编程方式为TextInputLayout设置提示文本颜色和浮动标签颜色.

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

在所附的屏幕截图中,我希望提示文本地址1 在未聚焦时为红色,并且在焦点上浮动标签地址1 应为红色.

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.

推荐答案

我通过反射更改了聚焦颜色.这是可能对某人有帮助的代码段.

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();
    }
}

编辑2018-08-01:

如果您使用的是设计库v28.0.0及更高版本,则字段已从mDefaultTextColor更改为defaultHintTextColor,并且从mFocusedTextColor更改为focusedTextColor.

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.

这篇关于以编程方式设置TextInputLayout提示文本颜色和浮动标签颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆