如何在运行时更改整个应用程序的主题颜色

时间:2019-07-11 10:36:46

标签: android android-layout

我正在尝试在运行时更改应用程序的颜色,即工具栏,状态栏,视图的颜色(我正在使用colorPrimary的颜色)。更改应该出现在每个活动中,而不仅仅是一个活动中。

我在这个问题上泛滥了,但显然人们还没有找到解决此问题的解决方案。到目前为止,我已经能够在运行时setTheme(theme)更改当前活动而不是所有活动的主题。

我也尝试使用属性来遵循this tutorial

根据本教程,我创建了一个attr.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <attr name="themeColorPrimary" format="reference"/>
    </resources>

style.xml

  <style name="IndigoTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="themeColorPrimary">@color/black</item>
        <item name="colorPrimary">?themeColorPrimary</item>
        <item name="colorPrimaryDark">?themeColorPrimary</item>
        <item name="colorAccent">@color/colorAccent</item>
   </style>

然后在每项活动中,我都试图更改根布局的背景以及状态栏颜色和工具栏颜色。我可以使用此方法成功更改每个活动中的背景颜色,但还不能更改状态栏颜色和工具栏颜色。

activity_main和another_activity

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="20dp"
        android:background="?themeColorPrimary"
        tools:context=".MainActivity">

</RelativeLayout>

BaseActivity.java

这是活动Java文件,我的所有活动文件都以BaseActivity扩展。

public class BaseActvity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        setTheme(R.style.GreenTheme1);
//      recreate();
}
}

有人有什么想法可以帮助我实现这一目标吗?

0 个答案:

没有答案