我正在尝试创建一个按钮,该按钮在默认状态下具有自定义背景,但仍然使用其所运行的任何设备特定的按下/选定状态的颜色.
从查看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添加到你的自定义样式中.
标签:android,button,colors
来源: https://codeday.me/bug/20190710/1421556.html