Jetpack Compose中的屏幕宽度和高度

100

我想知道如何使用Jetpack Compose获取屏幕的宽度和高度?

是否有其他方法可以检索屏幕尺寸,而不是使用getWindowManager().getDefaultDisplay()

6个回答

210

您可以使用LocalConfiguration.current实现此目的:

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

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

  ...

}


因为某些奇怪的原因,即使我从横屏切换到竖屏,LocalConfiguration 仍然给出了横屏方向的 screenWidth。有其他人遇到这个问题吗? - Ali_Waris
8
如果您想获取以像素为单位的大小:val screenDensity = configuration.densityDpi / 160f 并且乘以 dp,例如 val screenHeight = configuration.screenHeightDp.toFloat() * screenDensity。您可能还想将其四舍五入为整数,因为 px 是 Int 类型。 - lenooh
13
获取像素大小的更好方式可能是:val density = LocalDensity.current; val configuration = LocalConfiguration.current; val screenWidthPx = with(density) {configuration.screenWidthDp.dp.roundToPx()} 这段代码中,density 储存了设备的密度信息, configuration 储存了设备的配置信息。通过使用 with 函数和 roundToPx() 方法,可以将屏幕宽度从 dp 转换为像素(px)并储存在变量 screenWidthPx 中。 - Aragorn Crozier
@AragornCrozier 这个 .roundToPx() 是从哪里来的? - undefined
1
@hippietrail 这是在 Density.kt 文件中的一个函数。 - undefined
请注意,“screenHeightDp”不包括文档中所述的插图区域:“以dp单位表示的可用屏幕空间的高度,不包括窗口插图区域,如状态栏、导航栏和切口区域。” - undefined

7

其他的解决方法包括:

A.) 在层次结构的最高级别上声明一个BoxWithConstraints,然后在该盒子范围内访问maxHeight和等效宽度属性。

B.) 使用自定义布局。

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

6
我不认为这是最好的方法,但你可以尝试这样做:
class Size {
    @Composable
    fun height(): Int {
        val configuration = LocalConfiguration.current
        return configuration.screenHeightDp
    }
    @Composable
    fun width(): Int {
        val configuration = LocalConfiguration.current
        return configuration.screenWidthDp
    }
}


然后像这样使用这些值:
val size = Size()
val screenHeight = size.height()

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


2

解决方案

我正在使用这种方法来获取 ScreenWidthScreenHeight。这对我很有效,你也可以在 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
    
}

1
根据这里在Android文档中的说明:
"因为可组合项不是屏幕级可组合项,我们也不应直接使用当前窗口度量,以便最大限度地提高可重用性。"
使用BoxWithConstraints,您将获得实际可用的尺寸,而不是全屏尺寸。
这在某些情况下非常方便,比如当您有填充时。
@Composable
fun Card(/* ... */) {
    BoxWithConstraints {
        if (maxWidth < 400.dp) {
            Column {
                //...
            }
        } else {
            Row{
              //...
            }
        }
    }
}

它给你一个maxWidth和一个maxHeight来创建你的逻辑。更多信息请参考这个Android文档

希望对你有所帮助!


-1

这段代码对我有效

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接