screen width and height in jetpack compose

Viewed 20312

I am wondering how to get the screen width and height with Jetpack Compose? is there anyway you can retrieve the screen dimension other than getWindowManager().getDefaultDisplay()?

Thanks in advance...

2 Answers

You can achieve this with LocalConfiguration.current:

@Composable
fun PostView() {
  val configuration = LocalConfiguration.current

  val screenHeight = configuration.screenHeightDp.dp
  val screenWidth = configuration.screenWidthDp.dp

  ...

}

Other workarounds include:-

A.) Declaring a BoxWithConstraints at the highest level of the hierarchy, then accessing the maxHeight and equivalent width attributes exposed inside the scope of the box

B.) Using custom layouts

Layout(
 content = { ... }
){ measurables, constraints ->
 //Exposes constraints.maxWidth, and a height equivalent
}
Related