<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="@dimen/radius_default"/>
<solid
android:color="@color/alpha"/>
<stroke
android:width="1dp"
android:color="@color/red"/>
</shape>
我想在运行时更改笔画的颜色。
我使用了这段代码,但它没有用。
Drawable drawable = getResources().getDrawable(R.drawable.border_red);
drawable.setColorFilter(Color.BLUE), PorterDuff.Mode.SRC_ATOP);
container.setBackground(drawable);
如何更改笔画的颜色?
float[] outerR = new float[] { 12, 12, 12, 12, 0, 0, 0, 0 };
RectF inset = new RectF(6, 6, 6, 6);
float[] innerR = new float[] { 12, 12, 0, 0, 12, 12, 0, 0 };
ShapeDrawable biggerCircle = new ShapeDrawable(new RoundRectShape(outerR,inset, innerR));
biggerCircle.setIntrinsicHeight( 60 );
biggerCircle.setIntrinsicWidth( 60);
biggerCircle.setBounds(new Rect(30, 30, 30, 30));
biggerCircle.getPaint().setColor(Color.BLUE);
border.setBackgroundDrawable(biggerCircle);
我还没有重构,但这段代码对我有用。谢谢
答案 0 :(得分:2)
运行时形状看起来不像xml那么好,但我们可以创建形状,我们可以改变它的背景颜色和边框颜色。
我创建了一个可能对你有帮助的方法
public static LayerDrawable getDrawable(Shape shape, int colorBGNormal, int colorBorderNormal, int defaultStrokeWidth) {
Drawable[] layers = new Drawable[2];
ShapeDrawable background = new ShapeDrawable();
ShapeDrawable backgroundBorder = new ShapeDrawable();
background.setShape(shape);
background.getPaint().setColor(colorBGNormal);
background.getPaint().setAntiAlias(true);
backgroundBorder.setShape(shape);
backgroundBorder.getPaint().setColor(colorBorderNormal);
backgroundBorder.getPaint().setStyle(Style.STROKE);
backgroundBorder.getPaint().setStrokeWidth(defaultStrokeWidth);
backgroundBorder.getPaint().setAntiAlias(true);
layers[0] = background;
layers[1] = backgroundBorder;
return new LayerDrawable(layers);
}
答案 1 :(得分:2)
这个为我工作,给了我圆形的颜色
ShapeDrawable biggerCircle= new ShapeDrawable( new OvalShape());
biggerCircle.setIntrinsicHeight( 60 );
biggerCircle.setIntrinsicWidth( 60);
biggerCircle.setBounds(new Rect(30, 30, 30, 30));
biggerCircle.getPaint().setColor(Color.parseColor(first));//you can give any color here
holder.firstcolor.setBackgroundDrawable(biggerCircle);
答案 2 :(得分:1)
首先使用getbackground()获取Drawable。
Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
// cast to 'ShapeDrawable'
ShapeDrawable shapeDrawable = (ShapeDrawable)background;
shapeDrawable.getPaint().setColor(getResources().getColor(R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
// cast to 'GradientDrawable'
GradientDrawable gradientDrawable = (GradientDrawable)background;
gradientDrawable.setColor(getResources().getColor(R.color.colorToSet));
}