android 如何编写AlertDialog Rtl?

umuewwlo  于 2023-01-03  发布在  Android
关注(0)|答案(2)|浏览(145)

如何基于设备区域设置更改组合对象的方向,如AlertDialog的内容?

wbgh16ku

wbgh16ku1#

您可以按如下方式更改LayoutDirection

CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl ) {
        ...
    }

您可以根据语言环境更改LayoutDirection.RtlLayoutDirection.Ltr,您可以从

LocalContext.current.resources.configuration.locales
tp5buhyn

tp5buhyn2#

实施材料3:

implementation 'androidx.compose.material3:material3:1.0.1'

将此函数与material3库一起使用(您可以将其他材质版本与此库一起使用):

@Composable
fun AlertDialogWithDirection(
    onDismissRequest: () -> Unit,
    confirmButton: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    dismissButton: @Composable (() -> Unit)? = null,
    icon: @Composable (() -> Unit)? = null,
    title: @Composable (() -> Unit)? = null,
    text: @Composable (() -> Unit)? = null,
    shape: Shape = AlertDialogDefaults.shape,
    containerColor: Color = AlertDialogDefaults.containerColor,
    iconContentColor: Color = AlertDialogDefaults.iconContentColor,
    titleContentColor: Color = AlertDialogDefaults.titleContentColor,
    textContentColor: Color = AlertDialogDefaults.textContentColor,
    tonalElevation: Dp = AlertDialogDefaults.TonalElevation,
    properties: DialogProperties = DialogProperties()
) {
    val layoutDirection = LocalLayoutDirection.current
    AlertDialog(
        onDismissRequest,
        confirmButton = {
            CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) {
                confirmButton()
            }
        },
        modifier,
        {
            if (dismissButton != null)
                CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) {
                    dismissButton()
                }
        },
        icon,
        {
            if (title != null)
                CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) { title() }
        },
        {
            if (text != null)
                CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) { text() }
        },
        shape,
        containerColor,
        iconContentColor,
        titleContentColor,
        textContentColor,
        tonalElevation,
        properties
    )
}

并像这样使用:

AlertDialogWithDirection(
    onDismissRequest = { 

    },
    title = {
        Text(
            text = "Your Text"
        )
    },
    text = {
        Text(
            text = "Your Text"
        )
    },
    confirmButton = {
        Button(
            onClick = {
                ok()
            }
        ) {
            Text(
                text = "Button"
            )
        }
    },
    dismissButton = {
        OutlinedButton(
            onClick = { 
            }
        ) {
            Text(text = "Dismiss")
        }
    }
)

相关问题