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()?
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()?
 
    
     
    
    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
}
 
    
    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
}
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
    
}
 
    
    This code works for me
@Composable
fun displayMe(){
  val isTablet = ((LocalConfiguration.current.screenLayout
                 and Configuration.SCREENLAYOUT_SIZE_MASK)
                 >= Configuration.SCREENLAYOUT_SIZE_LARGE)
...
}
