虽然在res/drawable/下添加一个xml去实现某个button或者grid的selecto非常简单省事,如:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/focused_application_background" />
<item android:state_focused="true" android:drawable="@drawable/focused_application_background" />
<item android:state_focused="true" android:state_window_focused="true" android:drawable="@drawable/focused_application_background" />
<item android:drawable="@drawable/nomal_application_background" />
</selector>
但是,如果你的app需要换肤,这样种做法就行不通,只能通过代码的方式实现。
以上xml翻译成代码如下:
private StateListDrawable crateSelector(){
createDrawable();
final Drawable background = mWBCachedD_background.get();
final Drawable background_f = mWBCachedD_background_f.get();
final StateListDrawable drawable=new StateListDrawable();
drawable.addState(new int []{android.R.attr.state_pressed}, background_f );
drawable.addState(new int []{android.R.attr.state_focused}, background_f );
drawable.addState(new int []{android.R.attr.state_pressed , android.R.attr.state_window_focused}, background_f );
drawable.addState(new int []{}, background);
return drawable;
}