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

不操千曲而后晓声,观千剑而后识器。这篇文章主要讲述如何以编程方式制作可绘制的形状(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; }

另一答案【如何以编程方式制作可绘制的形状(Android)】换颜色:
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);


    推荐阅读