思路来源自http://blog.csdn.net/qinjuning/article/details/7474827
使用场景:按下和松开两种效果图片的替换,避免了繁琐的判断和赋值
selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/iconfont_kai"></item>
<item android:state_pressed="false" android:drawable="@drawable/iconfont_off"></item>
</selector>
main.xml:
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/selector"
android:layout_centerInParent="true" />
Main.java:
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageState(new int[]{android.R.attr.state_pressed}, true);
用处拓展,可以拓展selector.xml中的属性 来实现类似于item选中或未选中的效果
自定义效果示例:
attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="State" >
<attr name="state_ma" format="boolean" />
</declare-styleable>
</resources>
selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ma="http://schemas.android.com/apk/res-auto">
<item ma:state_ma="true" android:drawable="@drawable/iconfont_kai"></item>
<item ma:state_ma="false" android:drawable="@drawable/iconfont_off"></item>
</selector>
main.xml:
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img_state"
android:layout_centerInParent="true" />
Main.java:
ImageView img = (ImageView) findViewById(R.id.img);
// img.setImageState(new int[]{android.R.attr.state_pressed}, true);
img.setImageState(new int[]{R.attr.state_ma}, true);