我在从片段更改白天/夜间模式时遇到了一个问题,如果不重新创建父活动,模式不会更改,但我想从片段更改模式而不从当前片段移动。
public void setNightMode(Context target, boolean state){
//UiModeManager uiManager = (UiModeManager) target.getSystemService(Context.UI_MODE_SERVICE);
UiModeManager uiManager = (UiModeManager) getActivity().getSystemService(Context.UI_MODE_SERVICE);
if (state) {
//setTheme(R.style.DarkTheme);
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
//setting up Night Mode...
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
}
//uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
night_mode = false;
//homeBinding.toolbar.setHeaderColour(HomeActivity.this, false);
} else {
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
uiManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
}
night_mode = true;
}
}
更改夜间模式:
delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES
并更改为灯光模式:
delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO
要使用此功能,您必须实现 androidX appcompat 库
implementation 'androidx.appcompat:appcompat:1.4.0'
您能找到答案吗?