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);
}
}
});
}
}
This answer provides Android's adaptation to dark night mode. The dark theme is suitable for Android 10 (API level 29) and higher. This is a prerequisite.
For API 29 - API 30
If you want to enable dark night mode globally within the app, you need to meet the following conditions:
The corresponding Activity should inherit from AppCompatActivity.
Call the following code at the appropriate place to enable global dark mode in the application.
For API 31 and above
If you want to enable dark night mode globally within the app, you need to meet the following conditions:
Get UiModeManager .
Call the following code at the appropriate place to enable global dark mode in the application.