如何在运行时更改android应用程序主题?

如何解决如何在运行时更改android应用程序主题?

我正在尝试在运行时更改应用主题

我有ChangeTheme类和Utility(SharedPreferences)类

ChangeTheme.java

public class ChangeTheme extends AppCompatActivity {

    private final static int THEME_LIGHT = 1;
    private final static int THEME_DARK = 2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_theme_activity);
        updateTheme();
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.myoptions,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        switch (id){
            case R.id.theme:
                Intent toChangeTheme = new Intent(ChangeTheme.this,ChangeTheme.class);
                startActivity(toChangeTheme);
        }

        return true;
    }

    public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.lightTheme:
                if (checked){
                    setTheme(R.style.AppTheme);
                }

                    break;
            case R.id.darkTheme:
                if (checked){
                    setTheme(R.style.AppThemeDark);
                }

                    break;
        }
    }

    public void updateTheme() {
        if (Utility.getTheme(getApplicationContext()) <= THEME_LIGHT) {
            setTheme(R.style.AppTheme);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
            }
        } else if (Utility.getTheme(getApplicationContext()) == THEME_DARK) {
            setTheme(R.style.AppThemeDark);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                getWindow().setStatusBarColor(getResources().getColor(R.color.colorSecondary));
            }
        }
    }

}

change_theme_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="12dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp">

    <TextView
        android:id="@+id/textTheme"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Change Theme To:"
        android:layout_marginTop="125dp">
    </TextView>

    <RadioGroup
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="20dp">
        <RadioButton
            android:id="@+id/lightTheme"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Light Theme"
            android:onClick="onRadioButtonClicked"/>
        <RadioButton
            android:id="@+id/darkTheme"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dark Theme"
            android:onClick="onRadioButtonClicked"/>
    </RadioGroup>

</LinearLayout>

Utility.java

public class Utility {
    public static void setTheme(Context context,int theme) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        prefs.edit().putInt(context.getString(R.string.prefs_theme_key),theme).apply();
    }
    public static int getTheme(Context context) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        return prefs.getInt(context.getString(R.string.prefs_theme_key),-1);
    }
}

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppThemeDark" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorSecondary</item>
        <item name="colorPrimaryDark">@color/colorSecondaryDark</item>
        <item name="colorAccent">@color/colorSecondaryAccent</item>
    </style>

</resources>

当我单击按钮更改主题时,什么也没发生,为什么? 你能帮助我吗? 我已经检查过类似的问题,但无济于事

更新2020/09/08

ChangeTheme.java

public class ChangeTheme extends AppCompatActivity {

    private final static int THEME_LIGHT = 1;
    private final static int THEME_DARK = 2;
    private RadioButton lightThemeButton;
    private RadioButton darkThemeButton;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.change_theme_activity);

        lightThemeButton = (RadioButton) findViewById(R.id.lightTheme);
        darkThemeButton = (RadioButton) findViewById(R.id.darkTheme);
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.myoptions,ChangeTheme.class);
                startActivity(toChangeTheme);
        }

        return true;
    }

    public void onRadioButtonClicked(View view) {
        // Is the button now checked?
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.lightTheme:
                if (checked){
                    Utility.changeToTheme(this,Utility.THEME_LIGHT);
                }
                break;
            case R.id.darkTheme:
                if (checked){
                    Utility.changeToTheme(this,Utility.THEME_DARK);
                }
                break;
        }
    }
}

Utility.java

public class Utility {

    private static int sTheme;
    public final static int THEME_LIGHT = 0;
    public final static int THEME_DARK = 1;

    //Set the theme of the Activity,and restart it by creating a new Activity of the same type.
    public static void changeToTheme(Activity activity,int theme)
    {
        sTheme = theme;
        activity.finish();
        activity.startActivity(new Intent(activity,activity.getClass()));
    }

    //Set the theme of the activity,according to the configuration. */
    public static void onActivityCreateSetTheme(Activity activity)
    {
        switch (sTheme)
        {
            default:
            case THEME_LIGHT:
                activity.setTheme(R.style.AppTheme);
                break;
            case THEME_DARK:
                activity.setTheme(R.style.DarkTheme);
                break;
        }
    }
}

styles.xml

<color name="color_primary_grey">#212121</color>
<color name="color_primary_black">#000000</color>
<color name="color_accent_white">#aeaeae</color>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="DarkTheme" parent="AppTheme">
    <item name="colorPrimary">@color/color_primary_grey</item>
    <item name="colorPrimaryDark">@color/color_primary_black</item>
    <item name="colorAccent">@color/color_accent_white</item>
</style>

我现在要做什么才能在运行时更改主题?

解决方法

我以前是为了申请我的。

对于我的解决方案,我遵循了this guide中介绍的方法。

以下是要采取的步骤:

  1. 在共享首选项中保留主题的名称(或ID)。您已经做到了
  2. 在您活动的onCreate方法中,获取主题的字符串/ ID(以样式定义),该主题的字符串/ ID应该如下所示应用:
        // inside activities onCreate method
        // Within your switch command each case should look like this
        theme.applyStyle(R.style.AppColorsDefault,true) // in Java it should be getTheme()
        // for other cases just replace the style
        theme.applyStyle(R.style.AppColorsDark,true) // true forces overwriting attributes that are -potentially - defined by your AppTheme 
  1. 重新启动活动以进行更改(只能在onCreate方法中设置主题,因此您需要重新启动活动)
        val intent = requireActivity().intent // use Intent intent = getActivity().getIntent() in Java
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
        requireActivity().finish() // use getActivity() again
        startActivity(intent)

在我的解决方案中,您也不需要继承主题。应用的样式仅需要包含更改。 这里是一个例子:

styles.xml

<resources>

    <!-- Base application theme. 
         Also consider using a Material Theme
         Theme.MaterialComponents.Light.DarkActionBar
    -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <!-- put all the attributes here that should be applied to the app independent from the applied colors -->
    </style>

    <style name="AppColorsDefault">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>


    <style name="AppColorsDark">
        <item name="colorPrimary">@color/colorSecondary</item>
        <item name="colorPrimaryDark">@color/colorSecondaryDark</item>
        <item name="colorAccent">@color/colorSecondaryAccent</item>
    </style>

</resources>

如果您的应用程序具有多个活动,并且您希望将更改后的样式(例如颜色)应用于所有这些活动: 只需创建BaseActivity的{​​{1}},然后让您的所有活动扩展此extends AppCompatActivity

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-