如何在android compose中更改对话框的宽度

cuxqih21  于 2023-05-12  发布在  Android
关注(0)|答案(3)|浏览(371)

似乎不可能用编写来改变对话框的宽度。我最接近改变对话框宽度的方法是通过DialogProperties.usePlatformDefaultWidth。将其设置为false会导致对话框填满屏幕,但有没有办法使用自定义宽度?

ltqd579y

ltqd579y1#

Use可以使用带有texttitlebuttons参数的构造函数定义自定义AlertDialog,并应用size(例如Modifier.size)并使用usePlatformDefaultWidth = false覆盖默认行为:

AlertDialog(
    onDismissRequest = { /*TODO*/ },
    title = {
        Text(text = "Title")
    },
    text = {
        Text(
            "This area typically contains the supportive text " +
                    "which presents the details regarding the Dialog's purpose."
        )
    },
    buttons = {},
    properties = DialogProperties(
        usePlatformDefaultWidth = false
    ),
    modifier = Modifier.size(200.dp,250.dp)
)

von4xj4u

von4xj4u2#

如果你想在你的项目中使用一个固定的宽度,你可以创建一个自定义宽度的对话框,如下所示

@Composable
fun MyCustomDialog(
    onDismissRequest: () -> Unit,
    properties: DialogProperties = DialogProperties(),
    content: @Composable () -> Unit
) {
    Dialog(
        onDismissRequest = onDismissRequest,
        // We are copying the passed properties 
        // then setting usePlatformDefaultWidth to false
        properties = properties.let {
            DialogProperties(
                dismissOnBackPress = it.dismissOnBackPress,
                dismissOnClickOutside = it.dismissOnClickOutside,
                securePolicy = it.securePolicy,
                usePlatformDefaultWidth = false
            )
        },
        content = {
            Surface(
                color = Color.Transparent,
                modifier = Modifier.width(250.dp), // Customize your width here
                content = content
            )
        }
    )
}
ukxgm1gy

ukxgm1gy3#

您可以创建一个“DialogState”来设置Dialog的大小:

var isDialogOpen by remember { mutableStateOf(true) }
val dialogState = rememberDialogState(position = WindowPosition(x = 500.dp, y = 500.dp), size = DpSize(100.dp, 100.dp))
if (isDialogOpen){
    Dialog(title = "This is Dialog",
        state = dialogState,
        transparent = false,
        undecorated = false,
        resizable = false,
        onCloseRequest = {}) {
        Button(onClick = {
            isDialogOpen = false
        }) {
            Text("Close")
        }
    }
}

相关问题