I made settings activity from Android Studio, not manually. I want to make a switch that applies a dark mode in the app. The problem is that when I click the switch there is
Put this in your preferences.xml
:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<SwitchPreferenceCompat
app:defaultValue="false"
app:key="@string/key_night_mode"
app:summaryOff="@string/summary_night_mode_off"
app:summaryOn="@string/summary_night_mode_on"
app:title="@string/title_night_mode" />
</PreferenceScreen>
Then in your SettingsFragment.java
which extended PreferenceFragmentCompat
inside the onCreatePreference()
method:
SwitchPreferenceCompat switchPreferenceCompat = findPreference(getString(R.string.key_night_mode));
switchPreferenceCompat.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = false;
if (newValue instanceof Boolean)
isChecked = (Boolean) newValue;
if (isChecked) {
//these lines so that the preference persists
getPreferenceManager().getSharedPreferences().edit().putBoolean(getString(R.string.key_night_mode), true).apply();
//you do not need to finish and recreate activity
//it takes care of any such things that needs to be done
//automatically
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
getPreferenceManager().getSharedPreferences().edit().putBoolean(getString(R.string.key_night_mode), false).apply();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
return true;
}
});
These lines of codes are working for me.
Note:
AppTheme
should extends from Theme.AppCompat.DayNight
or Theme.MaterialComponents.DayNight
if you want to be dependent on platform for your night theme. Otherwise, you can create your separate Day
and Night
theme which extends from Theme.MaterialComponents.Light
and Theme.MaterialComponents
respectively(AppCompat
has similar set of themes too).Every time the app starts, it needs to respect the user's preferences and start in the user setted theme accordingly. To achieve this, you can check the preference and set theme in the MyApplication
class as follows:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean nightMode = sharedPreferences.getBoolean(getString(R.string.key_night_mode), false);
if (nightMode)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
else {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
else
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}