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>

以上兩種方案擇其一種即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM