【问题标题】:How to align a Box in Compose in the Center not just the Content如何在中心对齐 Compose 中的框而不仅仅是内容
【发布时间】:2023-01-26 18:40:39
【问题描述】:

这是我的代码! ;) 我的盒子在左上角对齐,但我希望盒子在中间。你知道我该怎么做吗?

OptIn(ExperimentalWearMaterialApi::class)
    @Composable
    fun OnTouch() {
        val width = 100.dp
        val squareSize = 50.dp
        val swipeableState = rememberSwipeableState(0)
        val sizePx = with(LocalDensity.current) { squareSize.toPx() }
        val anchors = mapOf(0f to 0, sizePx to 1) // Maps anchor points (in px) to states

        Box(
            contentAlignment = Alignment.Center, modifier = Modifier
                .width(width)
                .swipeable(
                    state = swipeableState,
                    anchors = anchors,
                    thresholds = { _, _ -> FractionalThreshold(0.3f) },
                    orientation = Orientation.Horizontal
                )
                .background(Color.LightGray)

        ) {
            Box(
                Modifier
                    .offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) }
                    .size(squareSize)
                    .background(Color.DarkGray)
            )
        }
    }

提前致谢 ! ;) 我确实搜索了文档,但一无所获......

【问题讨论】:

  • 哪一个? LightGray 或 DarkGray 盒子? LightGray 框的对齐方式取决于父容器。

标签: android kotlin android-jetpack-compose android-jetpack-compose-layout


【解决方案1】:

LightGray Box 的对齐方式取决于父容器。

例如,您可以使用 Column,例如:

Column(
    modifier = Modifier.fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    Box(
        contentAlignment = Alignment.Center, 
        modifier = Modifier
            //...
            .background(Color.LightGray)

    ) {
        //...
    }
}

【讨论】:

    猜你喜欢
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2014-06-07
    • 2015-09-12
    • 2013-07-05
    • 2021-12-26
    • 2020-03-01
    相关资源
    最近更新 更多