如何以编程方式制作可绘制形状 (Android)

How to make a drawable Shape programmatically (Android)

我正在制作自定义 TextView (Java class),但我遇到了问题 "to translate" 行(在 "original TextView" xml 上)

android:background="@drawable/myDrawableShape"

到java void 来改变"myDrawableShape"

的颜色

myDrawableShape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ffafafaf" />
<corners android:radius="15dp" />

我将从字符串中获取要设置的颜色,以编程方式更改颜色的空白可以是(例如)

void colorSet(String color)

提前致谢!

然后您可以使用以下代码在 Java 本身中创建 Shape Drawable。

public Drawable getRoundRect() {
    RoundRectShape rectShape = new RoundRectShape(new float[]{
            10, 10, 10, 10,
            10, 10, 10, 10
    }, null, null);

    ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
    shapeDrawable.getPaint().setColor(Color.parseColor("#FF0000"));
    shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
    shapeDrawable.getPaint().setAntiAlias(true);
    shapeDrawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
    return shapeDrawable;
}

更改颜色:

  TextView tv= (TextView) findViewById(R.id.txt_time);

    Drawable background = getResources().getDrawable(R.drawable.test);

    if (background instanceof ShapeDrawable) {
        // If 'ShapeDrawable'
        ShapeDrawable shapeDrawable = (ShapeDrawable) background;
        shapeDrawable.getPaint().setColor(ContextCompat.getColor(this,R.color.colorAccent));
    } else if (background instanceof GradientDrawable) {
        // If'GradientDrawable'
        GradientDrawable gradientDrawable = (GradientDrawable) background;
        gradientDrawable.setColor(ContextCompat.getColor(this,R.color.colorPrimary));
    } else if (background instanceof ColorDrawable) {
        // If ColorDrawable
        ColorDrawable colorDrawable = (ColorDrawable) background;
        colorDrawable.setColor(ContextCompat.getColor(this,R.color.colorPrimaryDark));
    }
    tv.setBackground(background);