This is my code in settings.java class. I have implemented my settings class like this. I want to make dark theme on and after killing the app it has to be present there as well and toggle has to be trued on.
Now I have achieved to make it dark. But when I kill the app and come again it gets disappeared. Toggle is also get turns off.
public class settings extends AppCompatActivity {
SwitchCompat switchCompat;
ImageView backbtn;
Button button;
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.Base_ThemeOverlay_AppCompat_Dark);
} else {
setTheme(R.style.Base_Theme_MaterialComponents_Light);
}
backbtn = findViewById(R.id.goingback);
LoadingDialod loadingDialod = new LoadingDialod(settings.this);
backbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
loadingDialod.startloadinganimation();
new Handler().postDelayed(new Runnable() {
@Override
public void run() { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Intent intent = new Intent(getApplicationContext(), settings.class);
startActivity(intent);
}
}, 800);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
});
}
}
I have already given an answer about this here but I am giving it here also:
Create a class named Preferences Manager
Paste this code in the class
Then in the fragment make an object named preferences manager like this.
PreferencesManager preferencesManager = new PreferencesManager(getActivity());Then add value to it like this
if night mode is set to on.
preferencesManager.putBoolean("NightMode",true);if night mode is off
preferencesManager.putBoolean("NightMode",false);and then later to check if night mode if on or off, use this code
Edit
Alternatively you can also use my library here to store the data. To store and retrieve, see the
README.mdfile