support library 23.2.0里在appcompat主題里添加了DayNight主題胰坟,可以根據(jù)系統(tǒng)時間在Theme.AppCompat (dark) 和 Theme.AppCompat.Light (light)切換。但是只對API14+以上的設(shè)備有效诈闺,API14以下的設(shè)備會默認使用light主題陪拘。
如何使用
<style name="MyTheme" parent="Theme.AppCompat.DayNight">
<!-- Blah blah -->
</style>
在程序中調(diào)用:
AppCompatDelegate.setDefaultNightMode()
參數(shù)的含義:
MODE_NIGHT_NO. Always use the day (light) theme.
MODE_NIGHT_YES. Always use the night (dark) theme.
MODE_NIGHT_AUTO. Changes between day/night based on the time of day.
MODE_NIGHT_FOLLOW_SYSTEM (default). This setting follows the system’s setting, which is essentially MODE_NIGHT_NO at the time of writing (more on this later).
在activity或者application中的靜態(tài)塊中設(shè)置default mode
static {
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_...);
}
public class MyApplication extends Application {
如果在application中設(shè)置了night mode厂镇,但是在某個component中要覆蓋night mode,可以調(diào)用:
public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Set the local night mode to some value
getDelegate().setLocalNightMode(
AppCompatDelegate.MODE_NIGHT_...);
// Now recreate for it to take effect
recreate();
}
}
}
在setcontentview之后設(shè)置night mode不會生效左刽,需要調(diào)用recreate
來重新創(chuàng)建activity捺信。
獲取當(dāng)前所處的night mode
AppCompatDelegate.getDefaultNightMode()
為了避免dark模式下字體顏色也為dark。盡可能使用theme attribute,比如
?android:attr/textColorPrimary. General purpose text color. Will be near-black on light theme, near-white on dark themes. Contains a disabled state.
?attr/colorControlNormal. General-purpose icon color. Contains a disabled state.
night mode specific 的資源放在values-night中
Refer:
https://medium.com/@chrisbanes/appcompat-v23-2-daynight-d10f90c83e94