Reputation: 2210
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 }
)
}
}
Upvotes: 18
Views: 33710
Reputation: 131
Late to the party, but if you add these two,
.width(IntrinsicSize.Min) & .height(IntrinsicSize.Min)
it's as if you added a wrap_content for the width and height
@Composable
fun TestScreen(modifier: Modifier = Modifier) {
Box(modifier = Modifier
.background(Color.Yellow)
.width(IntrinsicSize.Min)
.height(IntrinsicSize.Min)
) {
val switchState = remember { mutableStateOf(true) }
Switch(
checked = switchState.value,
enabled= true,
onCheckedChange = { switchState.value = it }
)
}
}
Upvotes: 4
Reputation: 67149
Box covers entire screen is probably something more sneaky because of Surface
with Modifier.fillMaxSize()
updates minimum Constraints of TestScreen
because it is direct descendent of Surface
.
Surface is a Box with propagateMinConstraints: Boolean = true
which forces minimum width and height to its direct descendent. This answer explains with examples how it works.
Your Composable is actually as this when parent is not Surface as i mentioned above.
Surface(
modifier = Modifier.fillMaxSize()
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(10.dp)
) {
TestScreen()
}
}
Upvotes: 6
Reputation: 6257
Since you haven't specified on what container/parent composable your posted composable is being called, I can only suggest using Modifier's wrapContentSize
.
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 }
)
}
Upvotes: 20