首页 > 解决方案 > 为按钮定义一个可绘制对象并根据所选的 MeterialDesign 主题对其进行更改

问题描述

我有一个 ImageButton,它使用 drawable/sampleimage.xml 作为源,我使用 MaterialDesign 作为我的应用程序主题。

我的按钮布局如下所示:

<ImageButton
        android:id="@+id/sampleButton"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/sampleimage.xml" />

我的styles.xml 看起来像这样:

<resources>
    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

我使用 Android 10 中的设置或使用

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

在安卓 9 上。

我不知道如何为我的按钮定义单个可绘制对象,该按钮会根据所选主题而变化。我想将 drawable/sampleimage_light.xml 用于浅色主题,而在使用深色主题时使用 drawable/sampleimage_dark.xml。

标签: androidandroid-studioandroid-layoutkotlinmaterial-design

解决方案


我的可绘制对象是矢量图像,所以我只是将填充颜色更改为 ?attr/colorOnSurface

我的drawable现在看起来像这样:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="?attr/colorOnSurface"
        android:pathData="M8,5v14l11,-7z"/>
</vector>

推荐阅读