AppComapt Day Night 模式

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Chapter 1 In the year 1878, I took my degree of Doctor of...
    foxgti阅读 3,895评论 0 6
  • The Great A.I. Awakening How Google used artificial intel...
    图羽阅读 1,331评论 0 3
  • 角色:一个囚人a 主人公w 小角色 1/2 导演n 演员y w被推进监狱 牢房里 有个长凳子凳子上坐着a w打招呼...
    莫永丶阅读 372评论 0 0
  • 术后第13天 做过的妹妹有没有这种心情,我刚开始没拆线的那几天,那几天的日子简直是我长这么大,过的最担心,最紧张的...
    鱼巷小岗阅读 307评论 0 0