在开发中,经常要对某一个控件的不同状态更换背景图片。例如:一个按钮按下的时候给它一个按下的效果,抬起按钮状态变回原来的样式。这时候我们可以用一个selector来实现。在我的Android学习 游戏开发之打地鼠(二,游戏设计和主界面设计)这篇博文中有如下一段代码:
/**
* 设置按钮按下和抬起的效果
*/
@Override
public boolean onTouch(View v, MotionEvent event) {
int id = v.getId();
switch (id) {
case R.id.startgame:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
start.setBackgroundResource(R.drawable.startgamean);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
start.setBackgroundResource(R.drawable.startgame);
}
break;
case R.id.rank:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
rank.setBackgroundResource(R.drawable.rankan);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
rank.setBackgroundResource(R.drawable.rank);
}
break;
case R.id.about:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
about.setBackgroundResource(R.drawable.aboutan);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
about.setBackgroundResource(R.drawable.about);
}
break;
case R.id.exit:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
exit.setBackgroundResource(R.drawable.exitan);
}
if (event.getAction() == MotionEvent.ACTION_UP) {
exit.setBackgroundResource(R.drawable.exit);
}
break;
default:
break;
}
return false;
}
看起来是复杂而且重复的,很low啊,现在用selector来改写这里的逻辑,这段代码可以省略了。
selector的使用步骤:
1,在drawable目录下新建一个xml文件,这里命名为bg_selector.xml,同时将要按钮按下和抬起的背景图片放在drawable目录下。
2,编写bg_selector.xml文件
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 按下的效果 -->
<item android:drawable="@drawable/selected" android:state_selected="true"></item>
<!-- 默认效果 -->
<item android:drawable="@drawable/usual"></item>
</selector>
设置好默认显示的图片和按下时显示的图片即可,这样一个selector就完成了,接下来就是使用了。
3,在布局文件中引用bg_selector.xml文件。
<ImageButton
<span style="white-space:pre"> </span>android:id="@+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector_button_bg" />
在background属性选择我们刚才建立好的xml文件即可。
很方便的一个东西,如果需要,我们可以给任何一个view对象都设置一个selector。