将可绘制形状的颜色更改为给定的 HEX

Change drawable shape's color to given HEX

我有以编程方式创建的 textView。他们需要有不同的颜色值。我不需要动画或任何花哨的东西,只需将给定的十六进制值(例如 FF00AB)应用于 textView 的可绘制形状:


list_item.xml

<TextView
        android:id="@+id/icon"
        android:background="@drawable/rounded_corner" />

rounded_corner.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/dummyColorValue" />
</shape>

ListAdapter.java

   // Set Icon Color
   String color "FF00AB";
   Drawable iconDrawable = txtIcon.getBackground();
// how to change the <solid android:color>-Value of iconDrawable HERE??

假设变量颜色的十六进制值是动态的。

问: setColorFilter() 是错误的方法还是我必须以某种方式转换字符串?

我想出的解决方案很少,它肯定能帮助你其中之一:

1

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

2

((GradientDrawable)someView.getBackground()).setColor(someColor);

3

   LayerDrawable bgDrawable = (LayerDrawable) button.getBackground();
final GradientDrawable shape = (GradientDrawable)
        bgDrawable.findDrawableByLayerId(R.id.round_button_shape);
shape.setColor(Color.BLACK);

4

    example.setBackgroundResource(R.drawable.myshape);
GradientDrawable gd = (GradientDrawable) example.getBackground().getCurrent();
gd.setColor(Color.parseColor("#000000"));
gd.setCornerRadii(new float[]{30, 30, 30, 30, 0, 0, 30, 30});
gd.setStroke(2, Color.parseColor("#00FFFF"), 5, 6);

希望对你有帮助:)