I implemented night mode in my app.User can change the night mode settings in profile activity.The order of activities are as follows.
TabbedActivity>>DisplayActivity,ProfileActivity
The changed settings are applied only in current activity.(i.e profile activity).If the user presses back button,changes are not applied to that activities.Anyone help me to apply changes to all the activites.When we close the app and open again.changes are applied.But back press doesn't work.
This is the code I am using.
@Override
protected void onCreate(Bundle savedInstanceState) {
final SharedPreferences sharedPreferences =
getSharedPreferences("NIGHT_MODE", MODE_PRIVATE);
int result=sharedPreferences.getInt("NIGHT_MODE_OPTION",0);
if (result==2){
setTheme(R.style.darkTheme);
}else setTheme(R.style.AppTheme);
loadLocale();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final SharedPreferences.Editor editor = getSharedPreferences("NIGHT_MODE", MODE_PRIVATE).edit();
if (result==2){
night.setChecked(true);
}
night.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
editor.putInt("NIGHT_MODE_OPTION",AppCompatDelegate.MODE_NIGHT_YES);
editor.apply();
startActivity(getIntent());
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
editor.putInt("NIGHT_MODE_OPTION",AppCompatDelegate.MODE_NIGHT_NO);
editor.apply();
startActivity(getIntent());
}
}
});
}
'i think the better practice would to restart/reset app everytime the theme is changed'
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();