1.如果您有这样的“视图”的可绘制文件
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="5dp" />
<solid android:color="@android:color/white" />
<stroke
android:width="3px"
android:color="@color/blue" />
</shape>
然后就可以换
一个了。描边颜色:
GradientDrawable drawable = (GradientDrawable)view.getBackground();
drawable.setStroke(3, Color.RED); // set stroke width and stroke color
湾。纯色 :
GradientDrawable drawable = (GradientDrawable)view.getBackground();
drawable.setColor(Color.RED); // set solid color
2.如果你有这样的“视图”的可绘制文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:id="@+id/buttonSelected">
<shape>
<solid android:color="@color/blue" />
<stroke android:width="1px" android:color="@color/blue" />
</shape>
</item>
<item android:state_checked="false" android:id="@+id/buttonNotSelected">
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<stroke android:width="1px" android:color="@color/blue" />
</shape>
</item>
</selector>
然后,您可以通过在该位置获取单独的可绘制对象来更改单个项目属性。
StateListDrawable drawable = (StateListDrawable)view.getBackground();
DrawableContainerState dcs = (DrawableContainerState)drawable.getConstantState();
Drawable[] drawableItems = dcs.getChildren();
GradientDrawable gradientDrawableChecked = (GradientDrawable)drawableItems[0]; // item 1
GradientDrawable gradientDrawableUnChecked = (GradientDrawable)drawableItems[1]; // item 2
现在改变描边或纯色:
//solid color
gradientDrawableChecked.setColor(Color.BLUE);
gradientDrawableUnChecked.setColor(Color.RED);
//stroke
gradientDrawableChecked.setStroke(1, Color.RED);
gradientDrawableUnChecked.setStroke(1, Color.BLUE);