如何在运行时使用 styles.xml 更改 Activity 的主题

How do I change the Activity's theme using styles.xml at runtime

styles.xml 中有 3 种不同类型的样式,如下所示:

<style name="Theme_A" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">#01AC50</item>
    <item name="colorPrimaryDark>#FF007838</item>
    <item name="colorAccent">#009688</item>"
<style>

用户可以使用按钮选择他们想要的样式,如何在单击按钮后更改整个 Activity 的样式

试试这个:-

您需要在 setContentView()

之前使用 setTheme() 函数

正如文档所说,您需要在视图实例化之前定义主题。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

     setTheme(android.R.style.Theme_Dark);
     .
     .
     setContentView(R.layout.main);
}

How to setTheme to an activity at runtime? It doesn't work call setTheme before onCreate and setContentView有建议使用

setContentView(...);
setTheme(R.style.MyTheme);
setContentView(...);

即:看来你需要在setThemeas

之后setContentView

[setTheme] should be called before any views are instantiated in the Context