Android 通过布局更改xml可绘制文件中形状的颜色

Android 通过布局更改xml可绘制文件中形状的颜色,android,android-layout,drawable,android-custom-view,Android,Android Layout,Drawable,Android Custom View,所以我创建了一个名为rounded_rect的可绘制xml文件。我最初将其颜色设置为红色。但是,我希望能够在布局文件中更改此颜色 rounded_rect.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="10dp"> &

所以我创建了一个名为rounded_rect的可绘制xml文件。我最初将其颜色设置为红色。但是,我希望能够在布局文件中更改此颜色

rounded_rect.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#ffff1900"/>
<corners
    android:bottomRightRadius="15dp"
    android:bottomLeftRadius="15dp"
    android:topLeftRadius="15dp"
    android:topRightRadius="15dp"/>

<stroke android:width="4dp"
    android:color="#000000"/>
</shape>
  • 也许我想得太多了。自由地在你的答案中发挥创造性。先谢谢你

您必须为每种颜色创建单独的绘图选项,因为无法在运行时设置这些属性,因为应用程序必须编译它们。

请尝试以下代码-

GradientDrawable bgShape = (GradientDrawable)yourview.getBackground();
        bgShape.setColor(Color.MAGENTA);
public class ItemView extends View {

    //attributes of item view
    private Drawable drawable;
    private String text;
    private int backgroundColor;

    private int width, height;
    private Paint paint;

    public ItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.ItemView, 0, 0);
        try {
            text = a.getString(R.styleable.ItemView_text);
            backgroundColor = a.getInteger(R.styleable.ItemView_backgroundColor, 0);
            drawable = a.getDrawable(R.styleable.ItemView_imagePath);
        } finally {

        }
        paint = new Paint();
        width = drawable.getMinimumWidth() / 2;
        height = drawable.getMinimumHeight() / 2;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //positions the image in the middle horizontally and a little above the text below
        drawable.setBounds(width / 4, height / 4 - 50, width - (width / 4),
                height - (height / 4) - 50);
        drawable.draw(canvas);

        paint.setTextSize(100);
        paint.setColor(Color.BLACK);
        canvas.drawText(text, width / 2 -
                paint.measureText(text, 0, text.length()) / 2, height - 50, paint);
    }
}
GradientDrawable bgShape = (GradientDrawable)yourview.getBackground();
        bgShape.setColor(Color.MAGENTA);