I am trying to enable Dark Night Mode in my App which is working though but when I restart the app it goes to again Light Mode basically I want to save Dark Night Mode State so when on restart app remain in Dark Mode once it is set to Dark mode, not in Light mode. My relevant code is given below:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_settings, container, false);
switchCompat= view.findViewById(R.id.switchCompat);
sharedPreferences = getActivity().getSharedPreferences("night",0);
Boolean booleanValue= sharedPreferences.getBoolean("night_mode",true);
if(booleanValue){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
switchCompat.setChecked(true);
}
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
switchCompat.setChecked(true);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("night_mode",true);
editor.commit();
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
switchCompat.setChecked(false);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("night_mode",false);
editor.commit();
}
}
});
return view;
I also tried this to activity but it is not saving the state of Dark Mode.