天天看點

android背景設定報錯 <item> tag requires a 'drawable' attribute or child tag defining a drawable<轉>

android背景設定報錯 tag requires a ‘drawable’ attribute or child tag defining a drawable<轉>

今天本來隻是想實作一個簡單的按下ImageButton背景變顔色的功能,結果碰到 tag requires a ‘drawable’ attribute or child tag defining a drawable的錯誤。這句話的意思很簡單,就是說item标簽下需要drawable屬性。在逛了無數國内論壇無果後,我嘗試進了一個英文網站,結果如醍醐灌頂,深深的感覺到國内和國外的差距。

The problem here is that you cannot define the background color using a color selector, you need a drawable selector. So, the necessary changes would look like this:

你不能将顔色選擇器用在background上,應該使用drawable selector,是以你應該這樣修改(假設檔案名為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/selected_state" /> </selector>awable/selected_state"/> </selector>

You would also need to move that resource to the drawable directory where it would make more sense since it’s not a color selector per se.

Then you would have to create the res/drawable/selected_state.xml file like this:

同時你也要将selected_state.xml放在drawable目錄下而不是color目錄,然後這樣定義res/drawable/selected_state.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/semitransparent_white" />
</shape>
           

and finally, you would use it like this:

最後在imageView中我們這樣定義background:

android:background=”@drawable/selector”

其實這種方法将selector和顔色的定義分開了 我們可以将selector和shape的定義放在一起:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#F1F1F1"/>
        </shape>
    </item>
    <item android:state_selected="true">
        <shape>
            <solid android:color="#F1F1F1"/>
        </shape>           
    </item>
</selector>