无法在Android的drawable xml中添加primary color属性。

6

我已经定义了我的主题为:

<style name="AppThemeRed" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimaryRed</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDarkRed</item>
        <item name="colorAccent">@color/colorAccentRed</item>
    </style>

在我的XML布局中,我正在进行以下操作:
<android.support.design.widget.AppBarLayout
        android:background="?attr/colorPrimary"
        android:id="@+id/topBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

无论我更改哪个主题,colorPrimary 颜色都会改变。 但是,如果我在 drawable 中添加相同的内容。
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="?attr/colorPrimary" />
            <corners android:radius="5dp"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="?attr/colorPrimary" />
            <corners android:radius="5dp"/>
        </shape>
    </item>
</selector>

出现"无法填充视图"错误,该视图的背景被设置为@drawabe/xxxx

我该如何在我的XML drawable中定义主题颜色属性?


请发布您的堆栈跟踪。 - Amey Shirke
你是否遇到过 android.view.InflateException: Binary XML file line... 的异常? - Charuක
@Charuka 是的,同样的错误。 - Muhammad Umar
我们不能在 <item> 中使用 android:color,需要使用 android:drawable 来设置背景。 - Charuක
@MuhammadUmar 我在我的答案中告诉了你如何定义drawable中的属性颜色...你可以根据自己的需要使用它。 - Abhishek Singh
显示剩余2条评论
4个回答

4

只需替换...

android:color="?attr/colorPrimary"

to...

android:color="@color/colorPrimaryRed"

更新

在API 21以下的版本中,无法引用xml drawable中的属性。 为了创建您的主题,您需要:

为每个主题创建一个xml drawable。 使用@color标签或#RGB格式直接将所需颜色包含在drawable中。

在attrs.xml中为drawable创建一个属性。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Attributes must be lowercase as we want to use them for drawables -->
    <attr name="my_drawable" format="reference" />
</resources>

将你的drawable添加到你的theme.xml中。

<style name="MyTheme" parent="@android:style/Theme.NoTitleBar">
   <item name="my_drawable">@drawable/my_drawable</item>
</style>

使用您的属性在布局中引用可绘制对象。

<TextView android:background="?my_drawable" />

我不想做那个 :) - Muhammad Umar
1
@Abi 你看到那个选择器的 XML 文件了吗?那是我想要修改的。布局的 XML 文件已经正常工作了。 - Muhammad Umar
android:background="?attr/colorPrimary" 这个可以用,<solid android:color="?attr/colorPrimary" /> 这个不行。 - Muhammad Umar
@MuhammadUmar 请尝试使用?colorPrimary?android:colorPrimary - Abhishek Singh

0

解决方法说它适用于21+ API,而我的最低要求是16。 - Muhammad Umar
可能有帮助:https://dev59.com/E2sz5IYBdhLWcg3wOVP5 - Amey Shirke

0

请问你能否尝试一下?

<solid android:color="@android:attr/colorPrimary"/>

替代

<solid android:color="?attr/colorPrimary" />

不起作用,伙计。第一个显然是21+,另一个是我正在做的事情,但会崩溃。 - Muhammad Umar

0

你可以使用 :-

<solid android:color="@android:color/holo_orange_dark"  />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接