每个按钮代表可点击的东西,它有一种颜色存储在数据库中,用户可以配置。按钮的背景是<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
centerColor
和 endColor
属性。我可以这样做:
button.getBackground().setTint(theColor);
但这似乎抹去了笔触和渐变。
这可能吗?有没有更好的办法?
最佳答案
试试下面的代码 fragment ,试一试
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);
关于android - 如何动态更改可绘制 <shape> 的颜色? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157145/