I am looking for a way to enable night mode programmatically with an Android code:
public static void setNightMode(Context target , boolean state){
UiM
SIMPLEST SOLUTION
You can enable/disable dark theme just by:
enable dark theme:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
forcefully disable dark theme:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
set app theme based on mobile settings of dark mode, i.e. if dark mode is enabled then the theme will be set to a dark theme, if not then the default theme, but this will only work in version >= Android version Q
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
Notes:
"Theme.AppCompat.DayNight"
like
<style name="DarkTheme" parent="Theme.AppCompat.DayNight">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
drawable & drawable-night,
values & values-night
Make sure to change the default theme from Theme.AppCompat.Light.DarkActionBar
to Theme.AppCompat.DayNight.DarkActionBar
in the styles.xml file and then do AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
to switch to the night mode. I have tested it in APIv23(Android 6.0) and above and it is working fine.
For a better explanation see this codelab by Android
NightOwl has its own implementation for switching day/night mode on Android. Getting started with NightOwl is super easy. Here's a code snippet:
Init the NightOwl in Application class,
NightOwl.builder().defaultMode(0).create();
Call three method in your Activity class,
public class DemoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// step1 before super.onCreate
NightOwl.owlBeforeCreate(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
// step2 after setContentView
NightOwl.owlAfterCreate(this);
// write your code
}
@Override
protected void onResume() {
super.onResume();
// step3 onResume
NightOwl.owlResume(this);
}
}
Switch skin everywhere as you like,
View v = findViewById(R.id.button);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NightOwl.owlNewDress(SettingActivity.this);
}
});