Ranjithkumar
Ranjithkumar

Reputation: 18416

How to set fillMaxWidth() for all childs in Jetpack Compose?

My problem:

I have multiple TextField in same page. I give the fillMaxWidth() in my rootView(column). But all child views width take it as wrap_content.

My code:

Column(
    verticalArrangement = Arrangement.SpaceAround,
    modifier = Modifier
        .padding(10.dp)
        .fillMaxWidth()//I give the max width here
        .fillMaxHeight()
) {

       MyTextField1()// No modifiers used
       MyTextField2()
       ...
 }

Output:

enter image description here

My question:

I have list of TextFields. So code simplicity I want to handle within rootView. It's any other option to fill the width for all child views?

Upvotes: 3

Views: 3040

Answers (2)

Phil Dukhov
Phil Dukhov

Reputation: 88222

You can't add some modifier which will be applied to all children without passing it directly.

But using Layout you can create custom column which will make all children fill max width and add spacing between:

@Composable
fun ColumnFillChildrenWidth(
    modifier: Modifier = Modifier,
    spacing: Dp = 0.dp,
    content: @Composable () -> Unit,
) {
    Layout(
        content = content,
        modifier = modifier
    ) { measurables, constraints ->
        var yOffset = 0
        val placeablesWithOffset = measurables.map {  measurable ->
            val placeable = measurable.measure(constraints)
            val result = placeable to yOffset
            yOffset += placeable.height + spacing.toPx().toInt()
            result
        }

        val totalViewHeight = placeablesWithOffset.sumOf { it.first.height }
        val totalSpacing = ((measurables.size - 1) * spacing.toPx()).roundToInt()
        layout(
            width = constraints.maxWidth,
            height = totalViewHeight + totalSpacing
        ) {
            placeablesWithOffset.forEach {
                val (placeable, offset) = it
                placeable.place(0, offset)
            }
        }
    }
}

Usage:

ColumnFillChildrenWidth(
    spacing = 20.dp,
    modifier = Modifier
        .fillMaxWidth()
        .padding(20.dp)
) {
    TextField(value = "", onValueChange = {})
    TextField(value = "", onValueChange = {})
    TextField(value = "", onValueChange = {})
}

Result:

Upvotes: 2

Sreekant Shenoy
Sreekant Shenoy

Reputation: 1640

You can create a modifier variable using Modifier.fillMaxWidth() and pass it to all child TextFields.

Column(
  ...
) {
    val maxWidthModifier = Modifier.fillMaxWidth()

    MyTextField1(maxWidthModifier)
    MyTextField2(maxWidthModifier)
    ...
}

...here applies.

@Composable
fun MyTextField1(modifier: Modifier) {
    TextField(
        ...
        //apply modifier
        modifier = modifier
    )
}

Upvotes: 0

Related Questions