Search code examples
androidxmlkotlinandroid-jetpack-composesize

Jetpack Compose: Setting fixed height of parent view


I'm converting code to Jetpack Compose. Dimensions of a particular container in recycler view are set by API response.

ViewContainer:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<TextView
        android:id="@+id/text_view_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="56dp"
        android:layout_marginRight="56dp"
        android:gravity="center"" />

Height setting code in ViewHolder:

                    container.layoutParams.height = item.containerHeight
//value of item.containerHeight is 600 dp

When I convert the code to the following Composable:

    Box(modifier = Modifier.height(item.containerHeight.dp).fillMaxWidth() {
    Text(
            modifier = Modifier.align(Alignment.Center).padding(start = 56.dp, end = 56.dp),
            text = ...,
            fontFamily = ...,
            fontSize = 18 sp
    )

The resulting text box is over 6 times the size of the version created by the XML even though they are both being given the same value for the height (600 dp). Why is this?


Solution

  • When you specify values programmatically in the LayoutParams, those values are expected to be pixels.

    Convert pixels to Dp:

    val dp = with(LocalDensity.current) {
      item.containerHeight.toDp()
    }