我試圖創建一個按鈕,該按鈕在默認狀態下具有自定義背景,但仍然使用特定於所運行的任何設備的按下/選定狀態的顏色。是否有一個Android API來獲取默認按鈕被按下/選擇的顏色?
從看的EditText源代碼,似乎沒有這樣的API,並且按下/選擇的顏色只是硬編碼:
public EditText(/*Context context, AttributeSet attrs, int defStyle*/) {
super(/*context, attrs, defStyle*/);
StateListDrawable mStateContainer = new StateListDrawable();
ShapeDrawable pressedDrawable = new ShapeDrawable(new RoundRectShape(10,10));
pressedDrawable.getPaint().setStyle(Paint.FILL);
pressedDrawable.getPaint().setColor(0xEDEFF1);
ShapeDrawable focusedDrawable = new ShapeDrawable(new RoundRectShape(10,10));
focusedDrawable.getPaint().setStyle(Paint.FILL);
focusedDrawable.getPaint().setColor(0x5A8AC1);
ShapeDrawable defaultDrawable = new ShapeDrawable(new RoundRectShape(10,10));
defaultDrawable.getPaint().setStyle(Paint.FILL);
defaultDrawable.getPaint().setColor(Color.GRAY);
mStateContainer.addState(View.PRESSED_STATE_SET, pressedDrawable);
mStateContainer.addState(View.FOCUSED_STATE_SET, focusedDrawable);
mStateContainer.addState(StateSet.WILD_CARD, defaultDrawable);
this.setBackgroundDrawable(mStateContainer);
}
任何人都可以驗證它是不可能的一個應用程序知道當前設備上按下/選擇的顏色是什麼?
如果應用程序無法確定按下/選擇的顏色是什麼,則無法爲與不同設備上的UI匹配的按鈕創建選擇器。
似乎Android必須提供一種方法來找出這些顏色是什麼,以便應用程序可以使用與正在運行的設備的UI一致的顏色。
謝謝!
-Tom B.
後續行動,以響應CaseyB的評論,我試過如下:
StateListDrawable d = new StateListDrawable();
d.addState(android.R.attr.state_enabled, getResources().getDrawable(R.drawable.my_custom_background));
myButton.setBackgroundDrawable(d);
但它會導致按鈕使用所有狀態的自定義背景。似乎沒有辦法告訴StateListDrawable使用按下/選定狀態的默認繪圖。
感謝您的回覆,但是創建一個有狀態的drawable並不會自動包含按下/選中狀態的默認drawable。我用我測試的有狀態可繪製代碼更新了我的原始文章。 – tombz 2010-10-08 18:37:52