java - 更改以编程方式生成的 TextInputLayout 的下划线颜色

标签 java android

我尝试更改以编程方式生成的 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);

结果:

enter image description here

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

最佳答案

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

关于java - 更改以编程方式生成的 TextInputLayout 的下划线颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59546742/

相关文章:

java - 如何分析 Domino 快照文件?

android - 谷歌护目镜 Intent

PhoneGap/DreamWeaver CS6 找不到 Android SDK

android - 如何禁用 Android snackbar 从底部屏幕打开动画

java - Eclipse 团队同步 - Workspace 和 Java Workspace (SVN) 之间的区别

java - 如何在 NetBeans 的 Debug模式下进入已实现的方法?

java - 如何使 ActionBean 立即实例化,但在我调用其中一个处理程序之后不实例化?

android - Firebase 聊天的左右对齐

php - 在android中使用okhttp将数组或jsonobject传递给php url?

java - 通过 JMX 查看 Ehcache 数据