我正在尝试以编程方式将 a 设置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);
但是,这不起作用:它总是绘制启用状态。我希望它在按下按钮时绘制Pressed状态。我究竟做错了什么?