簡體   English   中英

如何以編程方式制作可繪制的形狀(Android)

[英]How to make a drawable Shape programmatically (Android)

我正在制作一個自定義TextView(Java類),我很難“翻譯”該行(在“原始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" />

我將從String中獲取顏色,以編程方式更改顏色的void(例如)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM