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

问题描述:

我正在制作自定义TextView(Java类),并且在翻译"行时遇到麻烦(在原始TextView" xml上)

i'm making a custom TextView (Java class) and i'm having trouble "to translate" the line (on "original TextView" xml)

android:background="@drawable/myDrawableShape"

更改为Java void以更改"myDrawableShape"的颜色

to a java void to change the color of the "myDrawableShape"

myDrawableShape.xml

myDrawableShape.xml

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

我将从字符串中设置颜色,例如,以编程方式更改颜色的空缺可能是

I'll get the color to set from a String, the void to change the color programmatically could be (for example)

void colorSet(String color)

提前谢谢!

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

You can then create your Shape Drawable in Java itself using below code.

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