Get height of element Jetpack Compose

If you want to get the height of your button after composition, then you could use: onGloballyPositionedModifier.

It returns a LayoutCoordinates object, which contains the size of your button.

Example of using onGloballyPositioned Modifier:

@Composable
fun OnGloballyPositionedExample() {
    // Get local density from composable
    val localDensity = LocalDensity.current
    
    // Create element height in pixel state
    var columnHeightPx by remember {
        mutableStateOf(0f)
    }

    // Create element height in dp state
    var columnHeightDp by remember {
        mutableStateOf(0.dp)
    }

    Column(
        modifier = Modifier
            .onGloballyPositioned { coordinates ->
                // Set column height using the LayoutCoordinates
                columnHeightPx = coordinates.size.height.toFloat()
                columnHeightDp = with(localDensity) { coordinates.size.height.toDp() }
            }
    ) {
        Text(text = "Column height in pixel: $columnHeightPx")
        Text(text = "Column height in dp: $columnHeightDp")
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)