关联文章
- 换肤
-
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