89

I am wondering how to get the screen width and height with Jetpack Compose?

Is there any way you can retrieve the screen dimensions other than getWindowManager().getDefaultDisplay()?

Jonik
  • 80,077
  • 70
  • 264
  • 372

5 Answers5

188

You can achieve this with LocalConfiguration.current:

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

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

  ...

}

  • For some weird reason, LocalConfiguration is giving me screenWidth of landscape orientation even though I switched from Landscape to Portrait. Is anyone else facing this issue? – Ali_Waris Feb 03 '22 at 13:16
  • 8
    If you want to get the size in pixels: `val screenDensity = configuration.densityDpi / 160f` and multiply with dp, for example `val screenHeight = configuration.screenHeightDp.toFloat() * screenDensity`. You might want to `round` to a whole number as well. since px is `Int`. – lenooh Feb 16 '22 at 21:03
  • 11
    Probably a better way to get the size in pixels: `val density = LocalDensity.current; val configuration = LocalConfiguration.current; val screenWidthPx = with(density) {configuration.screenWidthDp.dp.roundToPx()}` – Aragorn Crozier Nov 04 '22 at 18:41
7

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
}
Richard Onslow Roper
  • 5,477
  • 2
  • 11
  • 42
5

I don't think it's the best way to do it but you can try this:

class Size {
    @Composable
    fun height(): Int {
        val configuration = LocalConfiguration.current
        return configuration.screenHeightDp
    }
    @Composable
    fun width(): Int {
        val configuration = LocalConfiguration.current
        return configuration.screenWidthDp
    }
}

and then use this values like that :

val size = Size()
val screenHeight = size.height()

Box(modifier = Modifier.height((screenHeigh/2).dp)) {
    //content
}

0

SOLUTION

I am using this approach to get ScreenWidth and ScreenHeight. This works well for me and you can also use this for making responsive UI in Jetpack Compose

@Composable
fun ScreenSizeHelper() {
    
    val context = LocalContext.current

    val displayMetrics = context.resources.displayMetrics
    
    //Width And Height Of Screen
    val width = displayMetrics.widthPixels
    val height = displayMetrics.heightPixels

    //Device Density
    val density = displayMetrics.density
    
}
Chirag Thummar
  • 665
  • 6
  • 16
-1

This code works for me

@Composable
fun displayMe(){
  val isTablet = ((LocalConfiguration.current.screenLayout
                 and Configuration.SCREENLAYOUT_SIZE_MASK)
                 >= Configuration.SCREENLAYOUT_SIZE_LARGE)
...
}