如何通过更改 android 中的主题来更改背景颜色?

how to change background color by changing the theme in android?

我想在android中更改主题时更改背景颜色。有没有办法像

那样在XML中设置背景
android:background="@styles/colorAccent"

因此,当我更改主题时,背景颜色会自动更改为相应主题的 colorAccent。任何替代方法也会有所帮助。

布局示例

 <FrameLayout
    style="@style/colorAccentStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content/>

styles.xml

<resources>

<style name="colorAccentStyle">
    <item name="android:background">?colorAccent</item>
</style>

更简单的解决方案

<FrameLayout
    android:background="?colorAccent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

使用此属性创建不同的主题

<style name="YourTheme" >
<item name="android:background">@color/yourcolor</item>
</style>

这将应用于没有手动设置背景的视图。

最后您可以通过

应用您的主题
getTheme().applyStyle(R.style.YourTheme, true);

setContentView

之前调用它