我正在使用 LinearLayout 作为我的 Android 应用程序中的父布局。根据不同的卡片类型,我动态地将各种卡片添加到LinearLayout中。其中一张卡是使用 Jetpack Compose 构建的,我在其中使用 LazyVerticalGrid 组件。
当我没有指定 LazyVerticalGrid 的最大高度时,应用程序崩溃并出现以下错误:
java.lang.IllegalStateException: Vertically scrollable component was measured with an infinity maximum height constraints, which is disallowed.
如果我设置固定高度(例如 400.dp),布局可以工作,但我希望它根据内容动态调整,而不需要对高度进行硬编码。
我尝试过的:
• Wrapping LazyVerticalGrid in Box or Column with Modifier.fillMaxHeight(), but it still crashes without a max height.
• Works with a fixed height like 400.dp, but I need it to adjust dynamically.
关键代码片段:
cells = GridCells.Fixed(2),
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 400.dp) // Works with fixed height
) {
items(100) {
Text("Item $it")
}
}
问题:
如何使 LazyVerticalGrid 在 LinearLayout 中没有固定高度的情况下工作?有没有办法让它根据内容动态调整?
据我所知,如果不对高度进行硬编码,则无法在 fillMaxSize() 组件内拥有动态(惰性)列表。 我建议使用不同的方法而不是约束布局(盒子或列或脚手架或这些的组合)。另一种更复杂的方法是使用自定义布局,这可能有效,但需要您付出更多努力。