java - Android/Java:如何使用 int Color 设置 MaterialShapeDrawable 的背景颜色?
问题描述
我有一个带圆角的 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]);
不得不写这么多代码只是为了改变背景颜色真是太疯狂了......
感谢你的帮助 !
推荐阅读
- python - networkx 图的边缘标签不显示在 PyQt 嵌入式 matplotlib 中
- android - Android studio Artic fox 无法创建构建
- html - 使用 XSL 将 XML 转换为 HTMl 时丢失的值
- postgresql - 在需要比较运算符的 WHERE 子句中选择 count(*)
- security - 为什么 ModSecurity 会阻止外部链接?
- ruby - Selenium::WebDriver::Error::InvalidArgumentError:invalid 参数(会话信息:headless chrome=93.0.4577.82)
- ios - 虚幻引擎 4:如何在设备上设置虚拟键盘
- kubernetes - 如何在 prometheus 中获取最近 3 个月内运行的 pod
- java - javassist.CannotCompileException: [源错误] 找不到构造函数 org.apache.http.protocol.RequestUserAgent
- scala - akka 流式传输 kafka 消费者在几秒钟内停止