首页 > 解决方案 > 更改以编程方式生成的 TextInputLayout 的下划线颜色

问题描述

我尝试更改以编程方式生成的 TextInputLayout(不是 xml 生成的)的下划线颜色:

LinearLayout layout=findViewById(R.id.layout);
LinearLayout.LayoutParams lp_mw=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

TextInputLayout textInputLayout = new TextInputLayout(context);
textInputLayout.setLayoutParams(lp_mw);
TextInputEditText field = new TextInputEditText(context);
field.setLayoutParams(lp_mw);
textInputLayout.addView(field);

// change color
int[][] states = new int[][]{
    new int[]{-android.R.attr.state_focused},
    new int[]{ android.R.attr.state_focused},
    new int[]{}
};
int[] hintColors = new int[]{
    R.color.colorPrimary, // unfocused
    R.color.colorAccent, // focused
    R.color.colorPrimary, // default
};
// attempt 1
textInputLayout.setBackgroundTintList(new ColorStateList(states, hintColors));
// attempt 2
field.getBackground().setColorFilter(context.getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.SRC_ATOP);

layout.addView(textInputLayout);

结果:

在此处输入图像描述

下划线颜色根本没有改变,我做错了什么?

标签: javaandroid

解决方案


2020 年新年快乐。


实际上你没有使用颜色值,而是使用资源值

像下面这样使用getResources().getColor来获取颜色值。

int[] hintColors = new int[] {
    getResources().getColor(R.color.colorPrimary), // unfocused
    getResources().getColor(R.color.colorAccent), // focused
    getResources().getColor(R.color.colorPrimary) // default
};

并将下划线颜色设置为TextInputEditText如下所示:

ViewCompat.setBackgroundTintList(field, new ColorStateList(states, hintColors));

推荐阅读