Thread
#compose
    Indu

    Indu

    1 year ago
    I read a few threads which gave me more info to choose between Layout and BoxwithConstraints. I used Layout for constructing the following screen. Basically I'm changing the number of elements in a row depending on the width of the screen.
    We need to use BoxwithConstraints only if we need to design a completely different layout for the same screen design right?(eg.. for a tablet)
    @Composable
    fun LayoutContainer(modifier: Modifier=Modifier, content: @Composable () -> Unit){
    
        Layout(
            modifier = modifier,
            content = content
        ) { measurables, constraints ->
    
            var rowWidths = mutableListOf<Int>()
            var rowWidth = 0
            var maxRowElements = 0
            var layoutHeight = 0
            var layoutWidth = 0
            var index = 0
    
            val placeables = measurables.map { measurable ->
    
                val placeable = measurable.measure(constraints)
    
                if((rowWidth + placeable.width) < constraints.maxWidth){
                    rowWidth += placeable.width
                }else{
                    rowWidths.add(rowWidth)
                    ++index
                    rowWidth = 0
                    rowWidth += placeable.width
                }
    
                placeable
            }
    
            rowWidths.add(rowWidth)
            ++index
    
            layoutHeight = placeables[0].height * index
    
            layoutWidth = rowWidths.maxOf { it }
    
            maxRowElements =  layoutWidth/placeables[0].width
    
            var xPosition = 0
            var yPosition = 0
            var rowElements = 0
    
            layout(layoutWidth,layoutHeight){
                placeables.forEach {
                    if(rowElements >= maxRowElements){
                        xPosition = 0
                        yPosition += it.height
                        rowElements = 0
                    }
                    it.placeRelative(xPosition,yPosition)
                    xPosition = xPosition+it.width
                    ++rowElements
                }
            }
        }
    }
    Albert Chang

    Albert Chang

    1 year ago
    Basically use
    Layout
    whenever you can. If you can implement the design using
    Layout
    , then definitely no need to use
    BoxWithConstraints
    .
    Indu

    Indu

    1 year ago
    Ok.. Thanks @Albert Chang