Home > Blockchain >  Wrap Content in Jetpack Compose
Wrap Content in Jetpack Compose

Time:12-02

How to make the parent layout - Box wrap its content in Jetpack compose? The current implementation below fills the entire screen, I only want the Box to wrap around its child - Switch. How do I define wrap content for the Box?

@Composable
fun TestScreen(modifier: Modifier = Modifier) {
    Box(modifier = Modifier.background(Color.Yellow)){
        val switchState = remember { mutableStateOf(true) }
        Switch(
            checked = switchState.value,
            enabled= true,
            onCheckedChange = { switchState.value = it }
        )
    }
}

A Switch inside a Box

CodePudding user response:

What you see on screen is not about Modifier.wrapContentSize. Modifier.wrapContentSize and having no size Modifier returns same constraints. You can check out enter image description here

CodePudding user response:

Modifier has wrapContentSize that you can use.

    Box(
        modifier = Modifier
            .background(Color.Yellow)
            .wrapContentSize() // wrap content height and width
    ){
        val switchState = remember { mutableStateOf(true) }
        Switch(
            checked = switchState.value,
            enabled= true,
            onCheckedChange = { switchState.value = it }
        )
    }

enter image description here

  • Related