加减按钮操作
btn_add.setOnClickListener {
if (mScreenBrightness < (255 - ratio)) {
mScreenBrightness += ratio
} else {
mScreenBrightness = 255
}
setWindowBrightness(mScreenBrightness)
updateNum(mScreenBrightness)
}
btn_reduce.setOnClickListener {
if (mScreenBrightness > ratio) {
mScreenBrightness -= ratio
} else {
mScreenBrightness = 1
}
setWindowBrightness(mScreenBrightness)
updateNum(mScreenBrightness)
}
如果设置亮度的值大于255了,不会报错,但是会回到初始值
,所以加减操作的时候要判断一下最大值最小值。
接下来看一下核心方法setWindowBrightness
:
/**
- 设置当前应用屏幕亮度,只当前有效
*/
private fun setWindowBrightness(brightness: Int) {
val window = window
val lp = window.attributes
lp.screenBrightness = brightness / 255.0f
window.attributes = lp
}
很简单,设置window
的属性即可。
这个只会对当前页面有效,返回页面或退到后台,屏幕亮度都会恢复
到初始值状态。
updateNum
方法是更新页面显示:
/**
- 更新页面显示
*/
private fun updateNum(mScreenBrightness: Int) {
//转float 取四舍五入
val i: Int = (mScreenBrightness / (ratio