使用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 -> {
/* ... */
}
}
}
您可以像这样检查方向:
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
}
根据新的 androidx.compose.material3.windowsizeclass
库添加更新的答案。
您现在可以使用 WindowSizeClass
查询宽度和高度类。此库专门用于构建自适应布局,并在活动的大小/方向更改时自动重新组合布局。
此 API 会给出宽度和高度的粗略大小(COMPACT
、MEDIUM
、EXPANDING
)。这使得处理折叠式设备和大屏幕显示器变得容易。
以下是我编写的一个简单示例实现:
class MainActivity {
/* ...... */
setContent {
val windowSizeClass = calculateWindowSizeClass(this)
/* .... */
MyApp(windowWidthSizeClass = windowSizeClass.widthSizeClass, /* .... */ )
}
}
@Composable
fun MyApp(windowWidthSizeClass: WindowWidthSizeClass, /* ... */) {
when(windowWidthSizeClass) {
WindowWidthSizeClass.Expanded -> // orientation is landscape in most devices including foldables (width 840dp+)
WindowWidthSizeClass.Medium -> // Most tablets are in landscape, larger unfolded inner displays in portrait (width 600dp+)
WindowWidthSizeClass.Compact -> // Most phones in portrait
}
}
在这里,当windowWidthSizeClass
等于WindowWidthSizeClass.Expanded
时,我可以将布局设置为类似于横向的视图。
我可以使用WindowWidthSizeClass.Medium
宽度来优化我的布局,以适应更大的设备,如平板电脑和可折叠设备。
最后,WindowWidthSizeClass.Compact
告诉我,大多数移动设备都是竖屏,因此我可以相应地更新我的UI。
这些相同的枚举也适用于活动的高度,但文档指出 -
大多数应用程序只需考虑宽度窗口大小类即可构建响应式UI。
(对我来说到目前为止是真的)
请注意,此库仍处于alpha版本,并明确标记为实验性,因此可能会发生变化。
示例实现可以在JetNews示例应用程序中找到 - https://github.com/android/compose-samples/tree/main/JetNews。
发布说明(发布于1.0.0-alpha10,当前版本-alpha13)- https://developer.android.com/jetpack/androidx/releases/compose-material3#1.0.0-alpha10
LocalConfiguration.current
来访问,它返回一个Configuration
对象。orientation
,
LocalConfiguration.current.orientation
同样,还有另外两个属性。
LocalConfiguration.current.screenWidthDp
LocalConfiguration.current.screenHeightDp
这将有助于您在组合的签名中使用它,而不必在其范围内执行相同的操作。例如,这可以用于修改器(Modifiers)以相应地调整组合。Modifier
,我建议使用fillMaxHeight(/*fraction/*)
和fillMaxWidth(/*fraction*/)
。正如明显的那样,分数是它应该占用父组合空间的一部分。如果父组合是setContent
,或者如果父组合伸展到整个屏幕(例如,使用fillMaxSize()
修改器的Surface
),那么这将相对于屏幕尺寸本身。因此,fillMaxHeight(0.1f)
将使组合的高度等于屏幕高度的十分之一。您可以在这里学习基本概念:compose-pathway。这可能并不是非常简单,但可以帮助构建更好的声明式范例基础。