修改Jetpack Compose 自带Dialog的透明度
修改
自带的Dialog默认没有背景变暗,用以下方式可以实现。
@Composable
fun DiaAmountLayout(
content: @Composable DiaAmountWindowScope.() -> Unit
) {
DiaAmountWindowScopeInstance.content()
}
interface DiaAmountWindowScope {
@Composable
fun SetDiaAmount(dimAmount: Float)
}
private object DiaAmountWindowScopeInstance : DiaAmountWindowScope {
@Composable
override fun SetDiaAmount(dimAmount: Float) {
val curView = LocalView.current
/* 更改dialog window的透明度 */
LaunchedEffect(curView,dimAmount) {
try {
val window = curView.findWindow() ?: return@LaunchedEffect
val lp = window.attributes
lp.dimAmount = dimAmount
window.attributes = lp
} catch (e: Throwable) {
e.printStackTrace()
}
}
}
/**
* 此代码逻辑来自 ComposeInputMethodManager.kt 下的[androidx.compose.foundation.text2.service.ImmHelper30]
*/
private tailrec fun Context.findWindow(): Window? = when (this) {
is Activity -> window
is ContextWrapper -> baseContext.findWindow()
else -> null
}
private fun View.findWindow(): Window? =
(parent as? DialogWindowProvider)?.window ?: context.findWindow()
}
测试
@Composable
fun Test(){
var dimAmount by remember {
mutableStateOf(1f)
}
var show by remember() {
mutableStateOf(false)
}
LaunchedEffect(Unit) {
while (isActive){
delay(1000)
dimAmount-=.2f
if (dimAmount<0f){
dimAmount = 1f
}
}
}
Column(
Modifier
.fillMaxSize()
.background(Color.Red)) {
Text(
text = "dimAmount=$dimAmount",
modifier = Modifier
.clickable {
show = !show
}
)
if (show) {
Dialog(onDismissRequest = { show = false }) {
DiaAmountLayout{
SetDiaAmount(dimAmount = dimAmount)
Box(
Modifier
.size(200.dp)
.background(Color.White), contentAlignment = Alignment.Center) {
Column {
Text(text = "hello")
}
}
}
}
}
}
}
或者
@Composable
fun LaunchDiaAmount(dimAmount: Float) {
val curView = LocalView.current
/* 更改dialog window的透明度 */
LaunchedEffect(curView, dimAmount) {
try {
val window = curView.findWindow() ?: return@LaunchedEffect
val lp = window.attributes
lp.dimAmount = dimAmount
window.attributes = lp
} catch (e: Throwable) {
e.printStackTrace()
}
}
}
/**
* 此代码逻辑来自 ComposeInputMethodManager.kt 下的[androidx.compose.foundation.text2.service.ImmHelper30]
*/
private tailrec fun Context.findWindow(): Window? = when (this) {
is Activity -> window
is ContextWrapper -> baseContext.findWindow()
else -> null
}
private fun View.findWindow(): Window? =
(parent as? DialogWindowProvider)?.window ?: context.findWindow()