关于setImageState(int[] state, boolean merge)的解释以及使用方式

来源:互联网 发布:怎么使用vim编译c语言 编辑:程序博客网 时间:2024/06/05 18:18

思路来源自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);





0 0