2010-09-21 52 views
16

我想在選擇器中使用Stlyle中定義的顏色,但它導致Resources $ NotFoundException。選擇器資源可以使用樣式中定義的顏色嗎?

首先,我增加了一個新的屬性attr.xml:

<resources> 
    <attr name="unread_background" format="color" /> 
</resources> 

然後我在styles.xml定義attr屬性值:

<style name="ThemeNoTitleBar" parent="android:Theme.NoTitleBar"> 
    <item name="unread_background">#000000</item> 
</style> 

然後我試圖使用attr屬性在我的選擇定義:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <!-- other states snipped --> 
    <item android:state_selected="false" 
     android:drawable="?unread_background" /> 
</selector> 

最後,該活動在清單中使用ThemeNoTitleBar樣式主題。

我也嘗試在colors.xml中創建一個顏色,並讓它使用新的attr,但也失敗了。

我明顯錯過了一些東西,但我不知道該怎麼做才能解決它。我的意圖是創建多個主題,並讓選擇器使用當前選定主題中的顏色。

回答

0

Android button with different background colors看看這個例子。看起來你需要這個。

+0

如果我更換unread_background用硬編碼的顏色值,然後正常工作,所以我不認爲其他答案適用於這裏。 – toddler 2010-09-21 14:53:40

+0

您是否爲您的問題找到答案?我也有同樣的問題。 – 2011-09-23 14:05:21

1
<item android:state_selected="false" 
    android:drawable="?unread_background" /> 

這段錯誤。

drawable僅引用可繪製資源。 請參閱此鏈接。 http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

+0

但是,根據文檔(http://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html#attr_android:src),BitmapDrawable 中的src屬性可以是主題屬性。 – 2012-07-31 07:24:08

+1

儘管該屬性是一個引用,並且樣式是可繪製的,但仍然會導致系統崩潰,因爲Android只允許在視圖中使用自定義屬性(?whatever)(至少這是我推斷的 - 我真的很想雖然錯了!) – HGPB 2012-08-24 21:00:20

1

這是一些東西,這是我的作品。

attrs.xml:

<attr name="color_selection" format="reference"/> 

styles.xml,作爲主旋律的孩子:

<item name="color_selection">@color/selection_background_inverse</item> 

shape_background_selected.xml在繪製文件夾:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="?attr/color_selection"/> 
</shape> 

您選擇的文件,在我的情況:selector_background_recyclerview:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@drawable/shape_background_selected" android:state_activated="true" /> 
    <item android:drawable="@drawable/shape_background_selected" android:state_pressed="true" /> <!-- pressed --> 
    <item android:drawable="@color/transparent" /> <!-- default --> 
</selector> 

最後,在您的視圖的XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:background="@drawable/selector_recyclerview_item_background"../>