androidandroid-jetpack-composeandroid-layout-weight

Issue with defining weight to views in Jetpack compose


I want to make a simple jetpack compose layout, using weights. below is the code

Row() {
Column(
    Modifier.weight(1f).background(Blue)){
    Text(text = "Weight = 1", color = Color.White)
}
Column(
    Modifier.weight(2f).background(Yellow)
) {
    Text(text = "Weight = 2")
}
}

which will result in a layout like this Simple row column lauout using weights.

but what if my inner views are coming from some other Composable function, which is unaware that its going to be a child of a column or a row?

Row() {
  // Calling Some composable function here
}

In that case i am not able to access the Modifier.weight(..) function, because it thinks that its not in the row or column scope, because it is an independent function.


Solution

  • You can add the modifier as parameter in your Composable.

    Something like:

    @Composable
    fun myCard(modifier: Modifier = Modifier, name:String){
        Box(modifier){
                Text(name,textAlign = TextAlign.Center,)
        }
    }
    

    In this way the myCard is unaware that its going to be a child of a Column or a Row.

    Then in your implementation you can use:

    Row(Modifier.padding(16.dp).height(50.dp)) {
        myCard(Modifier.weight(1f).background(Color.Yellow),"Weight = 1")
        myCard(Modifier.weight(2f).background(Color.Red),"Weight = 2")
    }
    

    enter image description here