如何判断系统深色模式是否开启并同步Switch开关状态?
判断系统深色模式状态并同步Switch控件选中状态
一、判断系统深色模式是否开启
要判断系统层面的深色模式状态,可通过读取系统配置的uiMode:
// 获取系统UI模式中的夜间模式标识 int currentSystemNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; // 判断是否开启系统深色模式 boolean isSystemDarkModeOn = currentSystemNightMode == Configuration.UI_MODE_NIGHT_YES;
如果你的App设置了跟随系统深色模式(MODE_NIGHT_FOLLOW_SYSTEM),上述代码直接生效;如果是手动指定了夜间模式(MODE_NIGHT_YES/MODE_NIGHT_NO),可直接通过AppCompatDelegate.getDefaultNightMode()判断:
boolean isAppDarkModeOn = AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES;
二、初始化Switch控件的选中状态
要让Switch控件在系统深色模式开启时自动选中,需先判断状态再设置监听(避免设置选中时触发监听重复执行模式切换逻辑),完整代码如下:
// 1. 判断当前深色模式状态 int appNightMode = AppCompatDelegate.getDefaultNightMode(); boolean shouldSwitchCheck; if (appNightMode == AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) { // 跟随系统时,取系统深色模式状态 int systemNightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; shouldSwitchCheck = systemNightMode == Configuration.UI_MODE_NIGHT_YES; } else { // 手动指定模式时,直接判断App当前模式 shouldSwitchCheck = appNightMode == AppCompatDelegate.MODE_NIGHT_YES; } // 2. 设置Switch选中状态 binding.switchh.setChecked(shouldSwitchCheck); // 3. 设置Switch的状态变化监听(原代码保留) binding.switchh.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean check) { if(check){ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); }else{ AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); } } });
三、监听系统深色模式动态变化(可选)
如果需要在用户切换系统深色模式时,自动同步Switch状态,需做以下两步:
- 在
AndroidManifest.xml的对应Activity标签中添加配置:
<activity ... android:configChanges="uiMode"> </activity>
- 在Activity中重写
onConfigurationChanged方法:
@Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); // 仅当App设置为跟随系统时,同步Switch状态 if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) { int systemNightMode = newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK; binding.switchh.setChecked(systemNightMode == Configuration.UI_MODE_NIGHT_YES); } }
内容的提问来源于stack exchange,提问作者nayan Ghodadara
相关产品推荐
相关产品推荐

