汤姆,
确实,如果您覆盖默认状态,您还必须覆盖按下和聚焦状态。原因是默认的 android 可绘制对象是一个选择器,因此用静态可绘制对象覆盖它意味着您丢失了按下和聚焦状态的状态信息,因为您只为它指定了一个可绘制对象。不过,实现自定义选择器非常容易。做这样的事情:
<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的来源,这就是他们设置背景drawable的方式:
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