首页 > 解决方案 > 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 还是其他方法?

谢谢。

标签: javaandroidtextview

解决方案


回答我的问题。

这是我添加的代码,以便能够设置任何背景颜色:

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

不得不写这么多代码只是为了改变背景颜色真是太疯狂了......

感谢你的帮助 !


推荐阅读