I'm making an Android app. I made another UI for dark mode. So this is what I need; the app will switch to dark theme automatically by the local time. For example, when the sun goes down by the local time, app will be switched to dark mode.
Or another alternative is switching to dark mode by pre-setted time of the day. Hope you understand my problem. Please help me if anyone knows, I prefer the first option to do if it's possible. Thanks in advance.
Maybe you can have a look at AppCompatDelegate.setDefaultNightMode()
you simply define your theme with the parent of DayNight:
<style name="MyTheme" parent="Theme.AppCompat.DayNight">
<!-- Blah blah -->
</style>
and each style with:
<style name="Theme.AppCompat.DayNight"
parent="Theme.AppCompat.Light" />
or
<style name="Theme.AppCompat.DayNight"
parent="Theme.AppCompat" />
and then you can call : AppCompatDelegate.setDefaultNightMode()
with one of these:
MODE_NIGHT_NO. Always use the day (light) theme.
MODE_NIGHT_YES. Always use the night (dark) theme.
MODE_NIGHT_FOLLOW_SYSTEM (default). This setting follows the system’s setting, which on Android Q and above is a system setting (more on this below).
MODE_NIGHT_AUTO_BATTERY. Changes to dark when the device has its ‘Battery Saver’ feature enabled, light otherwise.
MODE_NIGHT_AUTO_TIME & MODE_NIGHT_AUTO. Changes between day/night based on the time of day.
you would typically do this in your own custom application class:
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
}
}
more info here
Quick way:
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//restore preferences
SharedPreferences settings0 = this.getSharedPreferences(PREFS_NAME, 0);
lightMode = settings0.getBoolean("key0", true);
//retrieve selected mode
if (lightMode) {
//light mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
} else {
//dark mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
Switch switch0 = findViewById(R.id.Switch0);
switch0.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (darkMode) {
text = "Mode: light";
//light mode
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
darkMode = false;
} else {
text = "Mode: dark";
//dark mode
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
darkMode = true;
}
//save music preferences
SharedPreferences setting0 = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor0 = setting0.edit();
editor0.putBoolean("key0", darkMode);
editor0.apply();
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With