I have set Light and Dark mode in my app and its working.
But I also want to add an option to let the app follow the mode set by the system. So user can choose among three options.
I tried to do it, but was unsuccessful. I want to add Radio Buttons to switch to Light, Dark, Follow System Mode.
Here's what I have tried
public class setting extends AppCompatActivity {
private Switch darkMode;
Button autoButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
setTheme(R.style.darktheme);
}
else {
setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Settings");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setTitleTextAppearance(this, R.style.Font);
darkMode = (Switch) findViewById(R.id.darkModeSwitch);
autoButton = (Button) findViewById(R.id.autoButton);
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
darkMode.setChecked(true);
}
darkMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
getDelegate().applyDayNight();
recreate();
//restartApp();
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
recreate();
// restartApp();
}
}
});
}
}
There’s an option that does this: AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
.
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);