繁体   English   中英

应用程序重新启动后主题重置回系统

[英]Theme resets back to system after app is restarted

这是我用来在主题( LightDarkSet by System )之间切换的代码。 单击时我有单选按钮调用此功能:

public void setAppearance(View view) {
    int selected = Integer.parseInt(view.getTag().toString());

    if (selected == 0) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        sharedPreferences.edit().putString("appearance", "light").apply();
    } else if (selected == 1) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        sharedPreferences.edit().putString("appearance", "dark").apply();
    } else {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
        sharedPreferences.edit().remove("appearance").apply();
    }
}

这段代码完美运行。 但是,一旦我重新启动应用程序,它就会回到遵循系统主题。

我尝试在setContentView(R.layout.activity_home);之前添加它setContentView(R.layout.activity_home); Home Activity 的onCreate(Bundle savedInstanceState)中:

String theme = sharedPreferences.getString("appearance", "system");

if (theme.equals("light")) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else if (theme.equals("dark")) {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}

这似乎可以完成这项工作,但我注意到Home Activity启动了两次(加载时间也更长),当我单击后退按钮时,它显示了另一个Home Activity

解决这个问题的最佳方法是什么?

经过一番研究,我发现AppCompatDelegate.setDefaultNightMode(); 在应用程序运行时工作。 因此,每当您通过将所选主题保存在SharedPreferences重新启动它时,都必须再次设置它。 所以我面临的问题是我的活动的双重启动。 经过一些试验,我发现当我将代码放在super.onCreate(savedInstanceState);之前时它起作用了super.onCreate(savedInstanceState); 也是(不仅仅是setContentView(R.layout.activity_home); )。

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    String theme = sharedPreferences.getString("appearance", "system");

    if (theme.equals("light")) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    } else if (theme.equals("dark")) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    } else {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM