How to make a drawable Shape programmatically (Android)

给你一囗甜甜゛ 提交于 2020-04-08 14:42:07

问题


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"

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

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)

Thanks in advance!


回答1:


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



回答2:


Change Color:

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


来源:https://stackoverflow.com/questions/44401777/how-to-make-a-drawable-shape-programmatically-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!