我正在尝试以编程方式设置StateListDrawable
作为我的自定义视图的背景,用于一个库项目。这是我的操作:
final TypedArray a = getContext().obtainStyledAttributes(attrs,
R.styleable.ActionBar);
int firstColor = a.getColor(
R.styleable.ActionBar_backgroundGradientFirstColor, 0xff000000);
int secondColor = a
.getColor(R.styleable.ActionBar_backgroundGradientSecondColor,
0xff000000);
int textViewColor = a.getColor(R.styleable.ActionBar_titleColor,
0xffffffff);
int onClickColor = a.getColor(
R.styleable.ActionBar_backgroundClickedColor, 0xff999999);
a.recycle();
StateListDrawable sld = new StateListDrawable();
GradientDrawable drawable = new GradientDrawable(
Orientation.TOP_BOTTOM, new int[] { firstColor, secondColor });
sld.addState(new int[] { android.R.attr.state_enabled },
new ColorDrawable(onClickColor));
sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
action2.setBackgroundDrawable(sld);
action3.setBackgroundDrawable(sld);
actionBack.setBackgroundDrawable(sld);
pb.setBackgroundDrawable(drawable);
tv.setBackgroundDrawable(drawable);
tv.setTextColor(textViewColor);
然而,这并没有起作用:它总是绘制启用状态。当我按下按钮时,我希望它绘制按下状态。我做错了什么?