获取布局可组合项中计算的值并将其传递到子可组合项中

问题描述 投票:0回答:1

这是我的问题: 我有一个自定义布局

 Layout(content = content) { measurables, constraints ->
    val maxWidth = constraints.maxWidth
    val totalRows: Int = ceil(measurables.size / columnsCount.toFloat()).toInt()
    val itemWidth = maxWidth / columnsCount
    var itemHeight = 0 .....

我想使用像这样计算的

itemWidth

 CustomLayout(columnsCount = 4) { itemWidth ->
            for (team in state.teams) {
                MyComponent(
                        size = itemWidth,
                        team = team)}}

我该怎么做? 这样可以吗? 我可以使用哪些替代方案?

android android-layout android-jetpack-compose
1个回答
0
投票

假设您有这样的聊天记录:

现在您想要将每个可组合项的宽度设置为最宽可组合项的宽度

您可以使用 SubComposeLayout 获取每个子可组合项的高度/宽度,然后可以将这些值的大小调整为您想要的值。

@Composable
fun SubComposeLayoutDemo() {
ResizeWidthColumn(Modifier.fillMaxWidth(), true) {

    Box(
        modifier = Modifier
            .background(Color.Red)
    ) {
        Text("Hello")
    }

    Box(
        modifier = Modifier
            .padding(top = 8.dp)
            .background(Color.Red)
     ) {
        Text("This is a long messsage \n and its longer")
     }
   }
  }

  @Composable
  fun ResizeWidthColumn(modifier: Modifier, resize: Boolean, 
    mainContent: @Composable () -> Unit) {
         SubcomposeLayout(modifier) { constraints ->
     val mainPlaceables = subcompose(SlotsEnum.Main, mainContent).map {
        // Here we measure the width/height of the child Composables
        it.measure(Constraints())
     }

     //Here we find the max width/height of the child Composables
     val maxSize = mainPlaceables.fold(IntSize.Zero) { currentMax, 
     placeable ->
        IntSize(
            width = maxOf(currentMax.width, placeable.width),
            height = maxOf(currentMax.height, placeable.height)
        )
    }

    val resizedPlaceables: List<Placeable> =
        subcompose(SlotsEnum.Dependent, mainContent).map {
            if (resize) {
                /** Here we rewrite the child Composables to have the 
                 * width of
                 * widest Composable
                 */
                it.measure(
                    Constraints(
                        minWidth = maxSize.width
                    )
                )
            } else {
                // Ask the child for its preferred size.
                it.measure(Constraints())
            }
        }

    /**
     * We can place the Composables on the screen
     * with layout() and the place() functions
     */

    layout(constraints.maxWidth, constraints.maxHeight) {
        resizedPlaceables.forEachIndexed { index, placeable ->
            val widthStart = resizedPlaceables.take(index).sumOf { 
     it.measuredHeight }
            placeable.place(0, widthStart)
        }
    }
    } 
    }


    enum class SlotsEnum {
    Main,
    Dependent

    }

@Credit:https://foso.github.io/Jetpack-Compose-Playground/ui/layout/subcomposelayout/

© www.soinside.com 2019 - 2024. All rights reserved.