我想知道如何使用Jetpack Compose获取屏幕的宽度和高度?
是否有其他方法可以检索屏幕尺寸,而不是使用getWindowManager().getDefaultDisplay()
?
我想知道如何使用Jetpack Compose获取屏幕的宽度和高度?
是否有其他方法可以检索屏幕尺寸,而不是使用getWindowManager().getDefaultDisplay()
?
您可以使用LocalConfiguration.current
实现此目的:
@Composable
fun PostView() {
val configuration = LocalConfiguration.current
val screenHeight = configuration.screenHeightDp.dp
val screenWidth = configuration.screenWidthDp.dp
...
}
其他的解决方法包括:
A.) 在层次结构的最高级别上声明一个BoxWithConstraints
,然后在该盒子范围内访问maxHeight
和等效宽度属性。
B.) 使用自定义布局。
Layout(
content = { ... }
){ measurables, constraints ->
//Exposes constraints.maxWidth, and a height equivalent
}
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
}
解决方案
我正在使用这种方法来获取 ScreenWidth
和 ScreenHeight
。这对我很有效,你也可以在 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
}
BoxWithConstraints
,您将获得实际可用的尺寸,而不是全屏尺寸。@Composable
fun Card(/* ... */) {
BoxWithConstraints {
if (maxWidth < 400.dp) {
Column {
//...
}
} else {
Row{
//...
}
}
}
}
它给你一个maxWidth
和一个maxHeight
来创建你的逻辑。更多信息请参考这个Android文档。
希望对你有所帮助!
这段代码对我有效
@Composable
fun displayMe(){
val isTablet = ((LocalConfiguration.current.screenLayout
and Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE)
...
}
val screenDensity = configuration.densityDpi / 160f
并且乘以 dp,例如val screenHeight = configuration.screenHeightDp.toFloat() * screenDensity
。您可能还想将其四舍五入为整数,因为 px 是Int
类型。 - lenoohval density = LocalDensity.current; val configuration = LocalConfiguration.current; val screenWidthPx = with(density) {configuration.screenWidthDp.dp.roundToPx()}
这段代码中,density
储存了设备的密度信息,configuration
储存了设备的配置信息。通过使用with
函数和roundToPx()
方法,可以将屏幕宽度从 dp 转换为像素(px)并储存在变量screenWidthPx
中。 - Aragorn Crozier.roundToPx()
是从哪里来的? - undefinedDensity.kt
文件中的一个函数。 - undefined