Android @Compose 如何处理 Android 中的屏幕大小和方向。谷歌搜索后我无法找到合适的答案。有人可以回答这个问题。
3 回答
您可以像这样检查方向:
val configuration = LocalConfiguration.current
when(configuration.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> {}
Configuration.ORIENTATION_PORTRAIT -> {}
Configuration.ORIENTATION_SQUARE -> {}
Configuration.ORIENTATION_UNDEFINED -> {}
}
对于屏幕尺寸:
BoxWithConstraints() {
// thats what you can access:
this.maxWidth
this.maxHeight
this.minWidth
this.minHeight
}
1.0.x
您可以使用可BoxWithConstraints
组合项根据屏幕尺寸定义不同的 ui。
就像是:
BoxWithConstraints {
if (minWidth < 480.dp) {
/* .... */
} else if (minWidth < 720.dp) {
/* .... */
} else {
/* .... */
}
}
要处理方向,您可以使用LocalConfiguration
.
就像是:
val configuration = LocalConfiguration.current
when (configuration.orientation) {
Configuration.ORIENTATION_LANDSCAPE -> {
/* ... */
}
else -> {
/* ... */
}
}
}
这两个东西都可以在LocalConfiguration.current
返回Configuration
对象的帮助下访问。
如您所知,对于方向,存在一个属性orientation
,
LocalConfiguration.current.orientation
同样,还有其他两个属性。
LocalConfiguration.current.screenWidthDp
LocalConfiguration.current.screenHeightDp
这应该有助于您希望在 Composable 的签名中使用它而不是在其范围内执行相同操作的场景,例如,这可以在 Modifiers 中用于相应地调整可组合的大小。
但是,对于Modifier
s 用于调整 Composable 的大小,我建议使用fillMaxHeight(/*fraction/*)
andfillMaxWidth(/*fraction*/)
来代替。很明显,分数是它应该占据的父 Composable 空间的分数。如果父 Composable 是setContent
,或者如果父 Composable 拉伸到整个屏幕(例如,Surface
使用fillMaxSize()
修饰符),那么这将与屏幕尺寸本身相关。所以,fillMaxHeight(0.1f)
会让 Composable 的高度相当于屏幕高度的十分之一。您可以在此处使用compose-pathway来学习基本概念。它可能并不简单,但可能有助于为声明性范式建立更好的基础。