从查看 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 一致的颜色。
谢谢!
-汤姆 B.
后续,针对CaseyB的评论,我尝试了以下方法:
StateListDrawable d = new StateListDrawable();
d.addState(android.R.attr.state_enabled, getResources().getDrawable(R.drawable.my_custom_background));
myButton.setBackgroundDrawable(d);
但它会导致按钮为所有状态使用自定义背景。似乎没有办法告诉 StateListDrawable 为按下/选定状态使用默认可绘制对象。
最佳答案
最简单的方法是为继承自 android:style/Widget.Button
的按钮创建自定义样式并添加 android:background
到您的自定义样式。
关于android - 是否有 Android API 来获取默认按钮按下/选择的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3874779/