我有一个带圆角的 TextView。
这是我的代码:
float radius = 10f;
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED,radius)
.build();
MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);
ViewCompat.setBackground(textView,shapeDrawable);
现在,我想以编程方式更改 textView 的背景颜色。
当我这样做时:
shapeDrawable.setFillColor(ContextCompat.getColorStateList(this,R.color.design_default_color_background));
它有效;背景颜色已更改。
现在,我想使用像 Color.RED 这样的 int 颜色或使用 Color.RGB(r, g, b, a) 或 Color.RGB(r, g, b) 定义的任何随机颜色来更改背景颜色。
我怎样才能做到这一点?我应该使用 shapeDrawable.setFillColor 还是其他方法?
谢谢。
最佳答案
回答我的问题。
这是我添加的代码,以便能够设置任何背景颜色:
int[][] states = new int[][] {
new int[] { android.R.attr.state_hovered}, // hovered
};
int[] colors = new int[] {color};
ColorStateList myColorList = new ColorStateList(states, colors);
shapeDrawable.setFillColor(myColorList);
shapeDrawable.setState(states[0]);
为了改变背景颜色而必须编写这么多代码真是太疯狂了......
感谢大家的帮助!
关于java - 安卓/Java : how to set background color of MaterialShapeDrawable with int Color?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65006830/