[英]Is there an Android API to get the default button pressed/selected colors?
我正在嘗試創建一個按鈕,該按鈕在默認狀態下具有自定義背景,但仍然使用其所運行的任何設備特定的按下/選定狀態的顏色。
從查看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使用默認的drawables來處理按下/選擇的狀態。
最簡單的方法是為你的按鈕創建一個自定義樣式,繼承自android:style/Widget.Button
並將android:background
添加到你的自定義樣式中。
你應該使用有狀態的drawable,並讓它使用這些狀態的默認drawable。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.