将可绘制形状的颜色更改为给定的十六进制

时间:2019-01-31 13:24:46

标签: java android drawable

我有以编程方式创建的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 个答案:

答案 0 :(得分:2)

我想出的解决方案很少,它可以肯定地帮助您之一:

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

希望它对您有帮助:)