【问题标题】:Can a selector resource use a color defined in a style?选择器资源可以使用样式中定义的颜色吗?
【发布时间】:2011-04-15 00:50:57
【问题描述】:

我正在尝试在选择器中使用样式中定义的颜色,但它会导致 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>

然后我尝试在选择器定义中使用该属性:

<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,但这也失败了。

我显然遗漏了一些东西,但不知道该怎么做才能修复它。我的意图是创建多个主题并让选择器使用当前选定主题中的颜色。

【问题讨论】:

    标签: android


    【解决方案1】:
    <item android:state_selected="false"
        android:drawable="?unread_background" />
    

    以上部分是错误的。

    drawable 只引用可绘制资源。 请看这个链接。 http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

    【讨论】:

    • 但是,根据文档 (developer.android.com/reference/android/graphics/drawable/…),BitmapDrawable 中的 src 属性可以是主题属性。
    • 尽管如此,即使属性是引用并且样式是可绘制的,您仍然会导致系统崩溃,因为 Android 只允许在视图中使用自定义属性(?whatever)(至少这是我已经推断出 - 我真的想错了!)
    【解决方案2】:

    这里有一些东西,对我有用。

    attrs.xml:

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

    styles.xml,作为主题的子主题:

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

    drawable 文件夹中的 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"../>
    

    【讨论】:

      【解决方案3】:

      Android button with different background colors 看看这个例子。看起来你需要那个。

      【讨论】:

      • 如果我将 ?unread_background 替换为硬编码的颜色值,那么它可以正常工作,所以我认为其他答案在这里不适用。
      • 您找到问题的答案了吗?我也有同样的问题。
      猜你喜欢
      • 2021-09-15
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多