Compose中,AlertDialog圆角设置无效,或四角出现白色背景的解决方式

注:解决方式在最后。

一、问题复现

Compose Desktop,AlertDialog代码如下:

        AlertDialog(
            modifier = Modifier
                .clip(RoundedCornerShape(10.dp))
                .fillMaxHeight(0.3f)
                .fillMaxWidth(0.35f)
                .background(Color.White)
                .padding(20.dp),
            title = null,
            text = { /* 略 */ },
            buttons = { /* 略 */ }
        )

这里设置了RoundCornerShape圆角,弹出的对话框如图:
Compose中,AlertDialog圆角设置无效,或四角出现白色背景的解决方式_第1张图片

发现是没有圆角的。根据网上查到的信息,设置 AlertDialog 的背景为透明,无效。

当我给这个dialog设置背景色,如:

AlertDialog(
            modifier = Modifier
                .clip(RoundedCornerShape(10.dp))
                .fillMaxHeight(0.3f)
                .fillMaxWidth(0.35f)
                .background(Color.Red)  // 设置背景色为红色
                .padding(20.dp),
            title = null,
            text = { /* 略 */ },
            buttons = { /* 略 */ }
        )

结果如图:
Compose中,AlertDialog圆角设置无效,或四角出现白色背景的解决方式_第2张图片

可以看出,这多半是 AlertDialog 父组件的背景色,而不是 AlertDialog 自身的原因。

二、原因分析

根据 AlertDialog 的源码来看,其界面是通过 dialogProvider 来提供的。

fun AlertDialog(
    onDismissRequest: () -> Unit,
    buttons: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    title: (@Composable () -> Unit)? = null,
    text: @Composable (() -> Unit)? = null,
    shape: Shape = MaterialTheme.shapes.medium,
    backgroundColor: Color = MaterialTheme.colors.surface,
    contentColor: Color = contentColorFor(backgroundColor),
    dialogProvider: AlertDialogProvider = PopupAlertDialogProvider
) {
    with(dialogProvider) {
        AlertDialog(onDismissRequest = onDismissRequest) {
            AlertDialogContent(
                buttons = buttons,
                modifier = modifier.width(IntrinsicSize.Min),
                title = title,
                text = text,
                shape = shape,
                backgroundColor = backgroundColor,
                contentColor = contentColor
            )
        }
    }
}

dialogProvider 的默认实现是 PopupAlertDialogProvider,其中界面部分的代码如下:

Box(
    modifier = Modifier
        .fillMaxSize()
        .background(scrimColor)
        .pointerInput(onDismissRequest) {
            detectTapGestures(onPress = { onDismissRequest() })
        },
    contentAlignment = Alignment.Center
) {
    Surface(Modifier.pointerInput(onDismissRequest) {
        detectTapGestures(onPress = {
            // Workaround to disable clicks on Surface background https://github.com/JetBrains/compose-jb/issues/2581
        })
    }, elevation = 24.dp) {
        content()
    }
}

其中,对话框就是其中的 Surface 部分。而 Surface 的默认背景颜色就是白色。
问题找到了,就好解决了。

三、解决

  1. 新建一个 CustomDialogProvider,并复制 PopupAlertDialogProvider 的代码。
    将其中的 Surface 背景改为透明。
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.AlertDialogProvider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.awt.awtEventOrNull
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.type
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.*
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import java.awt.event.KeyEvent

@OptIn(ExperimentalMaterialApi::class)
object CustonDialogProvider : AlertDialogProvider {
    @Composable
    override fun AlertDialog(onDismissRequest: () -> Unit, content: @Composable () -> Unit) {
        // Popups on the desktop are by default embedded in the component in which
        // they are defined and aligned within its bounds. But an [AlertDialog] needs
        // to be aligned within the window, not the parent component, so we cannot use
        // [alignment] property of [Popup] and have to use [Box] that fills all the
        // available space. Also [Box] provides a dismiss request feature when clicked

        // outside of the [AlertDialog] content.
        Popup(
            popupPositionProvider = object : PopupPositionProvider {
                override fun calculatePosition(
                    anchorBounds: IntRect,
                    windowSize: IntSize,
                    layoutDirection: LayoutDirection,
                    popupContentSize: IntSize
                ): IntOffset = IntOffset.Zero
            },
            focusable = true,
            onDismissRequest = onDismissRequest,
            onKeyEvent = {
                if (it.type == KeyEventType.KeyDown && it.awtEventOrNull?.keyCode == KeyEvent.VK_ESCAPE) {
                    onDismissRequest()
                    true
                } else {
                    false
                }
            },
        ) {
            val scrimColor = Color.Black.copy(alpha = 0.32f) //todo configure scrim color in function arguments
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(scrimColor)
                    .pointerInput(onDismissRequest) {
                        detectTapGestures(onPress = { onDismissRequest() })
                    },
                contentAlignment = Alignment.Center
            ) {
                Surface(
                    Modifier.pointerInput(onDismissRequest) {
                        detectTapGestures(onPress = {
                            // Workaround to disable clicks on Surface background
                        })
                    },
                    elevation = 24.dp,
                    color = Color.Transparent  // 修改背景色为透明
                ) {
                    content()
                }
            }
        }
    }
}
  1. 在 AlertDialog 参数中,加入自定义的 DialogProvider。
        AlertDialog(
            modifier = Modifier
                .clip(RoundedCornerShape(10.dp))
                .fillMaxHeight(0.3f)
                .fillMaxWidth(0.35f)
                .background(Color.White)
                .padding(20.dp),
            dialogProvider = CustonDialogProvider,  // 添加自定义的 DialogProvider
            title = null,
            text = { /* 略 */ },
            buttons = { /* 略 */ }
        )

再次运行代码,发现圆角正常显示了:
Compose中,AlertDialog圆角设置无效,或四角出现白色背景的解决方式_第3张图片

当然,我们也可以通过在 Theme 中设置 Surface 的颜色,达到相同的效果:

    MaterialTheme(colors = MaterialTheme.colors.copy(surface = Color.Transparent)) {
        // 略
    }

不过这样就会改变所有Surface 的颜色了。

你可能感兴趣的:(android,kotlin,开发语言,compose)