负责您提到的选项的代码位于 onCreate() 中。允许用户更改模式的机制不在 onCreate() 中
public class MainActivityextends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
}
当您明确更改暗模式时,Android 会重新创建活动并因此onCreate
再次调用。
因此,在您更改暗模式后,您不会注意到更改,因为在系统AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
调用时再次onCreate
调用。
要使其正常工作,您可以在设置系统暗模式之前将值保存到SharedPreference
可以签入的值中。onCreate
这可以是一个布尔值,当您想要手动更改暗模式时可以切换它。
这是一个示例
public class MainActivityextends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSystem = prefs.getBoolean("IS_SYSTEM", true);
if (isSystem) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_color_mode) {
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
else
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean("IS_SYSTEM", false).apply();
return true;
}
}
更新
效果很好,但是当我退出应用程序然后再次启动时,尽管我已经切换了默认系统模式,但它仍然处于活动状态。有可能在这里使它以这种方式工作吗?
您可以使用另一个SharedPreference
布尔值永久保存
public class MainActivityextends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSystem = prefs.getBoolean("IS_SYSTEM", true);
boolean isNight = prefs.getBoolean("IS_NIGHT", false);
if (isSystem) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
} else if (isNight) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_color_mode) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
prefs.edit().putBoolean("IS_NIGHT", false).apply();
} else {
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
prefs.edit().putBoolean("IS_NIGHT", true).apply();
}
prefs.edit().putBoolean("IS_SYSTEM", false).apply();
return true;
}
}