val handler = Handler(Looper.getMainLooper())
// 蒙版控件id
val id = “darkMask”
// 打开夜间模式
if (lightOff) {
// 向主线程消息队列头部插入“展示蒙版”任务
handler.postAtFrontOfQueue {
// 构建蒙版视图
val maskView = View {
layout_id = id
layout_width = match_parent
layout_height = match_parent
background_color = color
}
// 向当前界面顶层视图中添加蒙版视图
decorView?.apply {
val view = findViewById(id.toLayoutId())
if (view == null) { addView(maskView) }
}
}
}
// 关闭夜间模式
else {
// 从当前界面顶层视图中移出蒙版视图
decorView?.apply {
find(id)?.let { removeView(it) }
}
}
}
为AppCompatActivity
扩展了一个方法,它用于开关夜间模式。打开夜间模式的方式是 “向当前界面顶层视图添加一个蒙版视图” 。
- 其中
decorView
是Activity
的一个扩展属性:
val Activity.decorView: FrameLa