Android 10.0夜间模式和换肤(备份)

关联文章
- 换肤

  • 全局灰度

  • compileSdkVersion 和 targetSdkVersion改29

  • 主题继承DayNight相关

  • 修改如values-night,drawable-night-xxhdpi之类的代表夜间模式的相应的文件夹

建议?android:attr/写,方便用换肤兼容不支持的设备

以下转载自
https://mp.weixin.qq.com/s/ovdBcrEIuxtM2YLH9Wx1uw

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/colorBackground">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Hello world"
        android:textSize="40sp"
        android:textColor="?android:attr/textColorPrimary" />

</FrameLayout>

是否深色模式

fun isDarkTheme(context: Context): Boolean {
    val flag = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
    return flag == Configuration.UI_MODE_NIGHT_YES
}

setDefaultNightMode()方法接收一个mode参数,用于控制当前应用程序的夜间模式。mode参数主要有以下值可供选择:

MODE_NIGHT_FOLLOW_SYSTEM:默认模式,表示让当前应用程序跟随系统设置来决定使用浅色主题还是深色主题。

MODE_NIGHT_YES:脱离系统设置,强制让当前应用程序使用深色主题。

MODE_NIGHT_NO:脱离系统设置,强制让当前应用程序使用浅色主题。

MODE_NIGHT_AUTO_BATTERY:根据手机的电池状态来决定使用浅色主题还是深色主题,如果开启了节点模式,则使用深色主题。

在MaterialTest当中,我们只需要使用如下代码就可以实现浅色主题和深色主题动态切换的功能:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        fab.setOnClickListener { view ->
            if (isDarkTheme(this)) {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            } else {
                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            }
        }
    }
    ...
}

生命周期不重走
android:configChanges=“uiMode”
主题变化会走onConfigurationChanged方法

override fun onConfigurationChanged(newConfig: Configuration) {
    val currentNightMode = newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK
    when (currentNightMode) {
        Configuration.UI_MODE_NIGHT_NO -> {} // 夜间模式未启用,使用浅色主题
        Configuration.UI_MODE_NIGHT_YES -> {} // 夜间模式启用,使用深色主题
    }
}

关于深色模式替换颜色写了个插件,见https://blog.csdn.net/u011208377/article/details/107043064

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值