Java 将主题应用于视图';背景色

Java 将主题应用于视图';背景色,java,android,xml,Java,Android,Xml,所以我有一个ImageButton,我可以把它的背景颜色改成白色,但是当使用深色主题时,它也会变成白色。我试着使用android:theme并将其设置为我的,但它将按钮的背景颜色设置为默认颜色,或者将整个应用程序的背景颜色更改为该颜色。 图像按钮: <ImageButton android:id="@+id/backbut" android:layout_width="45dp" android:layout_height="45dp&qu

所以我有一个ImageButton,我可以把它的背景颜色改成白色,但是当使用深色主题时,它也会变成白色。我试着使用android:theme并将其设置为我的,但它将按钮的背景颜色设置为默认颜色,或者将整个应用程序的背景颜色更改为该颜色。 图像按钮:

<ImageButton
android:id="@+id/backbut"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_margin="5dp"
android:layout_weight="0"
android:theme="@style/Theme.MusicPlayer"
android:contentDescription="@string/backbut_desc"
android:elevation="4dp"
android:padding="8dp"
android:scaleType="fitCenter"
app:srcCompat="@drawable/ic_arrow_left" />

themes.xml:

<resources xmlns:tools="http://schemas.android.com/tools">
<style name="Theme.MusicPlayer" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="colorPrimary">@color/blue_1</item>
    <item name="colorPrimaryVariant">@color/blue_1</item>
    <item name="colorOnPrimary">@color/white</item>
    <item name="colorPrimaryDark">@color/blue_2</item>
    <item name="colorAccent">@color/blue_1</item>
    <item name="android:textColorPrimary">@color/black</item>

    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryDark</item>
    <item name="android:navigationBarColor">@color/white</item>
</style>

@颜色/蓝色1
@颜色/蓝色1
@颜色/白色
@颜色/蓝色2
@颜色/蓝色1
@颜色/黑色
?属性/原色暗
@颜色/白色

关于我应该怎么做有什么建议吗?

以下是我处理此类案件的方法:

在attrs.xml中创建属性(在values文件夹中,如果没有,请自己创建),如下所示:


如果您在day-night主题的帮助下实现黑暗模式,则有2个themes.xml。因此,在位于values文件夹中的themes.xml文件中:

<item name="myBackgroundColor">#FFFFFF</item>
#FFFFFF
在位于values night文件夹的other themes.xml文件中:

<item name="myBackgroundColor">#000000</item>
#000000
当您希望视图根据手机主题相应地更改其背景色时:

<View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?myBackgroundColor"/>


就是这样,如果用户启用了暗模式,android将处理其余部分,并从night themes xml中选择您提供的相应颜色。

谢谢您的帮助!
<View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="?myBackgroundColor"/>