I have been trying to add a dark mode to my app and have mainly been using this site (Tutorial) to learn how to implement it. Everything works other than the theme does not change until I restart the app. After some research I have found that recreate() would be the correct way to fix this issue, but I do not know where to implement it.
Currently my oncreate method in the main activity looks like:
PreferenceManager.setDefaultValues(this, R.xml.settings_pref, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Boolean contrastPref = sharedPref.getBoolean (Navigation.KEY_PREF_CONTRAST_SWITCH, false);
setTheme(contrastPref? R.style.AppTheme_Dark : R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);........
With this just below the oncreate method
public static final String
KEY_PREF_CONTRAST_SWITCH = "contrast_switch";
The fragment that holds the preference switch looks like this:
public class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.settings_pref, rootKey);
}}
Thanks for the help :)
If you are changing theme from SettingFragment
then call getActivity().recreate()
from SettingFragment
.