support library 23.2.0里在appcompat主题里添加了DayNight主题,可以根据系统时间在Theme.AppCompat (dark) 和 Theme.AppCompat.Light (light)切换。但是只对API14+以上的设备有效,API14以下的设备会默认使用light主题。
如何使用
<style name="MyTheme" parent="Theme.AppCompat.DayNight">
<!-- Blah blah -->
</style>
在程序中调用:
AppCompatDelegate.setDefaultNightMode()
参数的含义:
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中的静态块中设置default mode
static {
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_...);
}
public class MyApplication extends Application {
如果在application中设置了night mode,但是在某个component中要覆盖night mode,可以调用:
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之后设置night mode不会生效,需要调用recreate
来重新创建activity。
获取当前所处的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
网友评论