java - 更改以编程方式生成的 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);
结果:
下划线颜色根本没有改变,我做错了什么?
解决方案
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));
推荐阅读
- haskell - 查找任何作为 int 的字符是否 > 127 的函数
- scala - Scala 函数文字
- javascript - 使用视图控制器淘汰嵌套的可观察对象
- swift - 应用在后台运行的自定义 URL 方案
- c - 如何访问用户定义数据类型中的数组元素?(C)
- javascript - div 边框可灵活调整大小,内部带有绝对定位的图像,纯 css/javascript
- html - 如何创建 Outlook 不为其文本换行的电子邮件?
- javascript - How to get DOM Node attributes in Angular
- php - Bootstrap 4 数据表 Javascript 库 2019
- apache-spark - 如何理解 Apache GraphX 的 pregel 实现中的 maxIterations