android - 如何动态更改可绘制 <shape> 的颜色? (安卓)

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

但这似乎抹去了笔触和渐变。

这可能吗?有没有更好的办法?

最佳答案

试试下面的代码 fragment ,试一试

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

关于android - 如何动态更改可绘制 <shape> 的颜色? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157145/

相关文章:

java - startAnimation(anim) 上的 NullPointerException

android - lateinit 属性 viewModelFactory 尚未在 Fragment 中初始化

android - 如何在对话框中使用两个以上的按钮

java - TextView 整数作为可绘制的 png

android以编程方式模糊可绘制的imageview

java - Draw() 还是 DrawBitmap()?

Android,特殊可绘制对象

android - 如何将 NFC 标签格式化为 NDEF 格式

android - 动态获取可绘制对象的原色以设置工具栏颜色

android - android studio中drawable文件夹的路径