[英]How to modify the default button state in Android without affecting the pressed and selected states?
我试图仅在默认状态下删除ImageButton的背景。 我希望按下和选择的状态像往常一样运行,以便它们在不同的设备上看起来正确,这些设备对按下和选择的状态使用不同的颜色。
有什么方法可以设置ImageButton的背景默认状态的drawable而不影响按下和选定的状态吗?
我尝试使用选择器来执行此操作,但是它似乎不允许您对某些状态使用默认可绘制对象-您必须自己设置所有状态。 由于没有API来检索设备的默认按下/选定的可绘制对象,因此我不知道将按下/选定的状态设置为什么。
我还尝试获取不使用选择器时系统创建的按钮的StateListDrawable对象,然后对其进行修改以更改默认状态。 那也不起作用。
我似乎在Android上,如果要更改按钮的一个状态的可绘制对象,则必须设置所有状态,因此无法保留其他状态的默认可绘制对象。 这个对吗?
谢谢! 汤姆·B
汤姆,
的确,如果您覆盖默认状态,则还必须覆盖按下状态和焦点状态。 原因是默认的android drawable是一个选择器,因此用静态drawable覆盖它意味着您只为其中指定了一个drawable,因此失去了按下状态和焦点状态的状态信息。 不过,实现自定义选择器非常容易。 做这样的事情:
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custombutton">
<item
android:state_focused="true"
android:drawable="@drawable/focused_button" />
<item
android:state_pressed="true"
android:drawable="@drawable/pressed_button" />
<item
android:state_pressed="false"
android:state_focused="false"
android:drawable="@drawable/normal_button" />
</selector>
将其放在您的drawables目录中,并像正常的drawable一样加载它作为ImageButton的背景。 对我而言,最难的部分是设计实际图像。
编辑:
只是做了一些深入研究EditText的来源,这就是他们设置背景可绘制的方式:
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);
}
我敢肯定,您可以根据自己的目的调整想法。 这是我在其上找到的页面:
http://www.google.com/codesearch/p?hl=en#ML2Ie1A679g/src/android/widget/EditText.java
StateListDrawable replace = new StateListDrawable();
Drawable old = getBackground();
replace.addState(FOCUSED_STATE_SET, old);
replace.addState(SELECTED_STATE_SET, old);
replace.addState(PRESSED_STATE_SET, old);
replace.addState(StateSet.WILD_CARD, new ColorDrawable(Color.TRANSPARENT));
if (Build.VERSION.SDK_INT >= 16) {
setBackground(replace);
} else {
setBackgroundDrawable(replace);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.