这是我用来在主题之间切换的代码(浅,深和由系统设置)。单击时我有单选按钮,请调用此功能:
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);
中的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活动。
解决此问题的最佳方法是什么?
答案 0 :(得分:0)
经过一番研究,我发现AppCompatDelegate.setDefaultNightMode();
在应用程序运行时有效。因此,每当您重新启动它时,都必须通过将所选主题保存在SharedPreferences
中来重新设置它。因此,我面临的问题是活动的双重启动。经过一番试验,我发现当我将代码放在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);
}