美文网首页高级UI
Android 深色主题适配

Android 深色主题适配

作者: AndroidLazy | 来源:发表于2020-06-12 16:03 被阅读0次

Android10系统开始,谷歌引入深色主题的特性,适配方案有两种,第一种是自动强制适配方案(Force Dark); 第二种是手动适配方案(资源替换)。

  1. Force Dark:
    在res目录下创建value-v29目录并创建styles.xml文件,复制一份你app style进去并添加<item name="android:forceDarkAllowed">true</item>,因为这个设置只能在Android系统10.0才能使用,所以不能直接设置在原来的app style,当程序运行在10.0以上系统才会读取value-v29目录。
<style name="AppTheme.NoActionBar">
       <!--标题栏的颜色-->
        <item name="colorPrimary">@color/colorPrimary_xueHui</item>
        <!--状态栏的颜色-->
        <item name="colorPrimaryDark">@color/colorPrimary_xueHui</item>
        <!--默认的光标、选中的RadioButton颜色-->
        <item name="colorAccent">@color/colorPrimary_xueHui</item>
         <item name="android:forceDarkAllowed">true</item>
    </style>

注意:
①. 如果使用的是 DayNight 或 Dark Theme 主题,则设置forceDarkAllowed 不生效。
②. 此种方案可能在深色主题颜色上会不尽人意,如果想在局部上排除适配的话可以对应的view上设置forceDarkAllowed为false。

  1. 手动适配方案:
    把你的app styles的parent指向DayNight主题,在这个主题下,开发者没有给控件颜色进行硬编码的话(没有设置颜色固定值),系统就会自动转换深色主题,然后针对那些进行了硬编码的颜色适配就需要进一步操作了,在res目录下创建value-night目录并创建colors.xml文件,然后在普通value目录下的colors的需要适配的颜色都复制一份到value-night目录下colors.xml并指定深色模式的具体颜色值,到这里就完成了,因为系统指定深色主题状态下会读取value-night目录。


    image.png

代码判断深色主题是否开启

public static boolean isNightMode(Context context) {
    int currentNightMode = context.getResources().getConfiguration().uiMode & 
        Configuration.UI_MODE_NIGHT_MASK;
    return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
}

监听深色主题是否开启

<activity
    android:name=".MyActivity"
    android:configChanges="uiMode" />
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    int currentNightMode = newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
    switch (currentNightMode) {
        case Configuration.UI_MODE_NIGHT_NO:
            // 关闭
            break;
        case Configuration.UI_MODE_NIGHT_YES:
            // 开启
            break;
        default:
            break;    
    }
}

相关文章

网友评论

    本文标题:Android 深色主题适配

    本文链接:https://www.haomeiwen.com/subject/gxzgtktx.html