如何动态更改可绘制<shape>的颜色? (机器人)

时间:2016-12-15 05:39:02

标签: android drawable android-drawable xml-drawable android-color

每个按钮代表可点击的内容,其中有一种颜色存储在用户可以配置的数据库中。该按钮的背景是随后的<shape>

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <stroke android:width="1dp" android:color="#000" />
  <corners android:radius="5dp" />
  <gradient android:startColor="#FFF"
            android:centerColor="#FFF"
            android:endColor="#666"
            android:angle="315" />
  <padding android:bottom="2dp"
           android:left="2dp"
           android:right="2dp"
           android:top="2dp" />
</shape>

我想了解<gradient>元素 - 特别是startColor centerColorendColor属性。我可以这样做:

button.getBackground().setTint(theColor);

但这似乎消除了中风和渐变。

这可能吗?还有更好的方法吗?

3 个答案:

答案 0 :(得分:2)

尝试下面的代码段,试一试

Have a look at this screenshot

GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(this,R.color.white), ContextCompat.getColor(this,R.color.red_500), ContextCompat.getColor(this,R.color.blue_500)});
    gd.setShape(GradientDrawable.RECTANGLE);
    gd.setStroke(1, ContextCompat.getColor(this, R.color.black));
    gd.setCornerRadius(5f);
    gd.setBounds(2, 2, 2, 2);
    findViewById(R.id.btn_analytics).setBackground(gd);

答案 1 :(得分:1)

请检查

GradientDrawable bgShape = (GradientDrawable)button.getBackground();
bgShape.setColor(Color.BLACK);

答案 2 :(得分:0)

正如之前的答案所指出的那样,它是一个GradientDrawable,它有一个花哨的setColors方法,允许按顺序直接访问这三个xml属性。但必须先调用mutate,如此:

GradientDrawable gd = ((GradientDrawable) button.getBackground());
gd.mutate();
gd.setColors(new int[]{dynamicColor,
   ContextCompat.getColor(context, R.color.button),
   ContextCompat.getColor(context, R.color.button_shade)});

@Bhavnik让我到了一半,谢谢。

相关问题