Android开发问题集锦-Button初始为disable状态时自定义的selector不生效问题

1.下面是不生效的布局:

  •  selector_btn_red.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    </item>
    <item android:state_pressed="true" android:drawable="@drawable/btn_red_pressed"></item>
    <item android:state_pressed="false" android:drawable="@drawable/btn_red_default"></item>
    <item android:state_enabled="false" android:drawable="@drawable/btn_red_default_disable">
</selector>

 

  • xxx_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myattr="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/download_item_padding" >

        <Button
            android:id="@+id/remove_btn"
            android:layout_width="match_parent"
            android:layout_height="@dimen/bottom_full_width_btn_height"
            android:layout_gravity="bottom"
            android:background="@drawable/selector_btn_red"
            android:enabled="false"
            android:text="@string/remove"
            android:visibility="visible" />
    </LinearLayout>

</LinearLayout>out>

2. 解析:按照初始的想法,这样的布局应当显示状态为enable=false的selector中指定的图(灰色)。但是事实不是这样的他显示了第一个(亮红)。为什么出现这种情况呢?这是因为android在解析selector时是从上往下找的,找到一个匹配的即返回。而我们第一个item中并没有指定enable,android认为满足条件返回了。

3.解决方法有两种:

  1). 交换item位置:

  

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_enabled="false" android:drawable="@drawable/btn_red_default_disable"></item>
    <item android:state_pressed="true" android:drawable="@drawable/btn_red_pressed"></item>
    <item android:state_pressed="false" android:drawable="@drawable/btn_red_default"></item>
    
</selector>

  2). 为每个item设置enable值:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item android:state_enabled="true" android:state_pressed="true" android:drawable="@drawable/btn_red_pressed"></item>
    <item android:state_enabled="true" android:state_pressed="false" android:drawable="@drawable/btn_red_default"></item>
    <item android:state_enabled="false" android:drawable="@drawable/btn_red_default_disable"></item>
</selector>

以上两种方案择其一种即可。

 

你可能感兴趣的:(Android开发问题集锦-Button初始为disable状态时自定义的selector不生效问题)