创建selector有两种方法,一种是定义xml文件,一种是创建StateListDrawable对象,完全可以用创建StateListDrawable来代替xml,它的好处是可以在程序运行时动态的调整背景颜色或者背景图片。
一.xml创建selector方法如下:
定义一个switch_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/switch_bg_disabled_emui" android:state_enabled="false"/>
<item android:drawable="@drawable/switch_bg_on_emui" android:state_pressed="true"/>
<item android:drawable="@drawable/switch_bg_on_emui" android:state_focused="true"/>
<item android:drawable="@drawable/switch_bg_on_emui" android:state_checked="true"/>
<item android:drawable="@drawable/switch_bg_off_emui"/>
</selector>
在Activity按下面方法使用
Drawable drawable = getResourse().getDrawable(R.drawable.switch_selector);
ImageView iv = new ImageView(this);
iv.setBackground(drawable);
二.用StateListDrawable来代替xml创建selector:
private StateListDrawable createDrawableSelector(Context context)
{
Drawable checked = context.getResources().getDrawable(R.drawable.switch_bg_on_emui);
Drawable unchecked = context.getResources().getDrawable(R.drawable.switch_bg_off_emui);
Drawable disabled = context.getResources().getDrawable(R.drawable.switch_bg_disabled_emui);
StateListDrawable stateList = new StateListDrawable();
int statePressed = android.R.attr.state_pressed;
int stateChecked = android.R.attr.state_checked;
int stateFocused = android.R.attr.state_focused;
int stateensable = android.R.attr.state_enabled;
stateList.addState(new int[] {-stateensable}, disabled);
stateList.addState(new int[] {stateChecked}, checked);
stateList.addState(new int[] {statePressed}, checked);
stateList.addState(new int[] {stateFocused}, checked);
stateList.addState(new int[] {}, unchecked);
return stateList;
}
其中stateList.addState()表示一个状态对应一个Drawable,在Activity里面按下面方法使用
Drawable drawable = createDrawableSelector(this);
ImageView iv = new ImageView(this);
iv.setBackground(drawable);