我想以编程方式创建选择器可绘制对象。形状必须采用以下形式:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"><shape>
<solid android:color="#4aa5d4" />
</shape></item>
<item><shape>
<stroke android:width="1dp" android:color="#4aa5d4" />
</shape></item>
</selector>
为什么?因为我希望这2种颜色可以改变。我知道我必须为此创建某种Drawable
。我已经设法这样创建自己的GradientDrawables
:
public GradientDrawable getBackgroundGradient() {
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] { BACKGROUND_GRADIENT_TOP_COLOR, BACKGROUND_GRADIENT_BOTTOM_COLOR });
return gd;
}
但是现在我需要一个SelectorDrawable。
好的,这是我使用链接主题想到的。
public StateListDrawable getSelectorDrawable(int color) {
StateListDrawable out = new StateListDrawable();
out.addState(new int[] { android.R.attr.state_pressed }, createNormalDrawable(color));
out.addState(StateSet.WILD_CARD, createStrokeDrawable(color));
return out;
}
public GradientDrawable createNormalDrawable(int color) {
GradientDrawable out = new GradientDrawable();
out.setColor(color);
return out;
}
public GradientDrawable createStrokeDrawable(int color) {
GradientDrawable out = new GradientDrawable();
out.setStroke(1, color);
return out;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句