java - 无法在android drawable xml中添加属性原色

标签 java android android-drawable android-styles

我的主题定义为

<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>

它因无法膨胀 View 而崩溃,该 View 的背景设置为 @drawabe/xxxx

如何在我的 XML 可绘制对象中定义主题颜色属性

最佳答案

只是替换...

android:color="?attr/colorPrimary"

为了...

android:color="@color/colorPrimaryRed"

更新

无法在 API 21 以下的 xml 可绘制对象中引用属性。 为了制作您的主题,您需要:

为每个主题创建一个 xml 可绘制对象。 直接使用@color 标签或#RGB 格式将所需的颜色包含到您的可绘制对象中。

在 attrs.xml 中为您的可绘制对象创建一个属性。

<?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>

将可绘制对象添加到 theme.xml。

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

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

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

关于java - 无法在android drawable xml中添加属性原色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41499168/

相关文章:

java - 我希望数据能够成功保存

java - 在哪里可以找到 Java 的语法高亮库?

android - nexus 6 和 moto g 的可绘制文件夹

android - 更改抽屉导航的图标

android - 设置 BitmapDrawable tileMode 使应用程序重新启动

java - jReddit Java 异常

android - 使用 expo-image-picker 选择图像时应用程序崩溃

android - android中的嵌套可扩展 ListView

安卓模拟器显示 "Device Nexus_5_Edited_API_23 [emulator-5554] is online, waiting for processes to start up.."

java - 为什么我的变量无法接收值(接口(interface))