我試圖編程設置一個StateListDrawable
作爲我的自定義視圖的庫項目的背景。下面是我在做什麼: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);
但是,這是行不通的:它總是得出啓用狀態。我想讓它畫出按下的狀態,當我按下時的按鈕。我究竟做錯了什麼?
以防萬一:使用XML是不是一種選擇,因爲我想這是儘可能定製(它是一個UI庫,所以我希望用戶能夠通過他們的XML定製它) – razielsarafan