我正在尝试以编程方式将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);但是,这不起作用:它总是绘制启用的状态。当我按按下按钮时,我希望它画出按下的状态。我做错了什么?
发布于 2012-10-05 13:58:08
我想按钮在按下的时候仍然是启用的?
您可以尝试倒序:
sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(new int[] { android.R.attr.state_enabled },
new ColorDrawable(onClickColor));可能正在绘制第一个当前有效的状态。
如果在按下时需要一个不同的背景,对于所有其他情况,也可以使用另一个背景:
sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(new int[] { StateSet.WILD_CARD },
new ColorDrawable(onClickColor));添加:我刚刚测试了这个,下面的测试代码适用于我:
Button testButton = new Button(context);
testButton.setText("Test");
StateListDrawable sld = new StateListDrawable();
GradientDrawable drawable = new GradientDrawable(
Orientation.TOP_BOTTOM, new int[] { Color.BLUE, Color.RED });
sld.addState(new int[] { android.R.attr.state_pressed }, drawable);
sld.addState(StateSet.WILD_CARD, new ColorDrawable(Color.YELLOW));
testButton.setBackgroundDrawable(sld);
mainLayout.addView(testButton);https://stackoverflow.com/questions/12745968
复制相似问题