Thrishool MSM
Thrishool MSM

Reputation: 347

Changes are not applied to all the activities

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());

            }
        }
    });

}

Upvotes: 0

Views: 776

Answers (2)

Muhmmad Umair
Muhmmad Umair

Reputation: 140

'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();

Upvotes: 0

Jasurbek
Jasurbek

Reputation: 2966

Since you are not considering Android lifecycle. You configure everything inside onCreate. However, while switching between activities current activity's lifecycle change accordingly. Here is lifecycle is explained very well

Solution:

When you come back to the previous activity, onResume is called. You should apply all changes inside this method

override fun onResume() {
   super.onResume()

   //Read your settings from SharedPrefs then apply, here
}

Upvotes: 1

Related Questions