我尝试更改以编程方式生成的 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));
关于java - 更改以编程方式生成的 TextInputLayout 的下划线颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59546742/