我正在制作一个自定义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" />
我将从字符串中获取要设置的颜色,以编程方式更改颜色的空格可能是(例如)
void colorSet(String color)
提前致谢!
答案 0 :(得分:5)
然后,您可以使用以下代码在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;
}
答案 1 :(得分:1)
更改颜色:
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);