Android深色模式适配

1、开启深色模式:
①、继承 DayNight 主题背景
<style name="BaseAppTheme" parent="Theme.AppCompat.DayNight">

②、MaterialComponent 的深色主题背景
<style name="BaseAppTheme" parent="Theme.MaterialComponents.DayNight">

③、Android 10 提供 Force Dark 功能(values-v29)

<resources>
    <style name="BaseAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- 启用 Force Dark -->
        <item name="android:forceDarkAllowed">true</item>
    </style>
</resources>


<application
        android:theme="@style/BaseAppTheme">
</application>

2、资源文件适配(只要配置对应深色模式资源,当系统开启深色模式,会自动显示深色模式资源)

drawable       ——>   drawable-night
mimap-xxhdpi   ——>   mimap-night-xxhdpi
values         ——>   values-night

如:
values——color.xml 
    <color name="text_white_color">#ffffff</color>
values-night——color.xml
    <color name="text_white_color">#000000</color>


3、Activity获取或者设置主题背景

设置主题背景
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
获取主题背景
int defaultNightMode = AppCompatDelegate.getDefaultNightMode();

如果不希望主题背景发生更改时Activity重新创建(android:configChanges="uiMode")

<activity
    android:name=".MyActivity"
    android:configChanges="uiMode" />


当主题发生变化时候Activity onConfigurationChanged方法会被调用

@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:
            // Night mode is not active, we're using the light theme
            Log.i(TAG, "onConfigurationChanged: light");

            break;
        case Configuration.UI_MODE_NIGHT_YES:
            // Night mode is active, we're using dark theme
            Log.i(TAG, "onConfigurationChanged: dark");
            break;
        default:
            break;
    }
}

一般app深色模式都是跟随系统的,所以只需要对资源文件进行适配即可

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值