2010-09-21 51 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"../>