我想以编程方式使用选择器状态而不是使用xml文件来更改ImageView背景(在我的情况下为渐变颜色)。
我希望将压缩和默认状态设置为我的ImageView
为了创建渐变背景,我使用以下代码:
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.BOTTOM_TOP,
new int[] {Color.parseColor(startColour), Color.parseColor(endColour)});
如何为此实现选择器?
由于
答案 0 :(得分:6)
这是来自我的应用:
public static Drawable getButtonDrawableByScreenCathegory(Context con,
ScreenCategory screenCategory, ButtonType buttonType) {
int normalStateResID = (int) GXConstants.NOT_ID;
int pressedStateResID = R.drawable.button_header_pressed;
switch (screenCategory) {
...
}
Drawable state_normal = con.getResources()
.getDrawable(normalStateResID).mutate();
Drawable state_pressed = con.getResources()
.getDrawable(pressedStateResID).mutate();
StateListDrawable drawable = new StateListDrawable();
drawable.addState(new int[] { android.R.attr.state_pressed },
state_pressed);
drawable.addState(new int[] { android.R.attr.state_enabled },
state_normal);
return drawable;
}
要为按钮设置背景,请致电:
button.setBackgroundDrawable(GXUtils.getButtonDrawableByScreenCathegory(
this, mScreenCategory, ButtonType.MENU)