android/java:如何用int color设置materialshapedrawable的背景色?

yiytaume  于 2021-07-06  发布在  Java
关注(0)|答案(3)|浏览(341)

我有一个圆角的文本视图。
这是我的密码:

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

它起作用了;背景色已更改。
现在,我想用一个int颜色来改变背景色,比如color.red,或者任何用color.rgb(r,g,b,a)或color.rgb(r,g,b)定义的随机颜色。
我该怎么做?我应该使用shapedrawable.setfillcolor还是其他方法?
谢谢。

ehxuflar

ehxuflar1#

您可以像这样定义颜色的全局值

public static final int RED = 0xffff0000;

像这样使用。

shapeDrawable.setFillColor(ContextCompat....(this, RED));
7jmck4yq

7jmck4yq2#

回答我的问题。
以下是我添加的代码,以便能够设置任何背景颜色:

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

疯狂地写这么多代码只是为了改变背景颜色。。。
谢谢大家的帮助!

sshcrbum

sshcrbum3#

方法 setFillColor 与一个 ColorStateList .
您可以使用以下方法:

int[][] states = new int[][] {
    new int[] { android.R.attr.state_focused}, // focused
    new int[] { android.R.attr.state_hovered}, // hovered
    new int[] { android.R.attr.state_enabled}, // enabled
    new int[] { }  // 
};

int[] colors = new int[] {
    Color.BLACK,
    Color.RED,
    Color....,
    Color....
};

ColorStateList myColorList = new ColorStateList(states, colors);

相关问题