如何在BottomSheetDialogFragment中正确使用Jetpack Compose?

问题描述 投票:0回答:2

例如,我在应用程序中有 MyBottomSheetDialogFragment 和 Compose LazyColumn 代码:

class MyBottomSheetDialogFragment : BottomSheetDialogFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setContent {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    Text("Header", color = Color.Black)
                    LazyColumn(
                        Modifier
                            .weight(1f)
                            .fillMaxWidth()) {
                        items(100) {
                            Text("Item $it", Modifier.fillMaxWidth(), Color.Black)
                        }
                    }
                }
            }
        }
    }
}

并使用此代码显示它:

MyBottomSheetDialogFragment().show(activity.supportFragmentManager, null)

这就是我们所拥有的:

MyBottomSheetDialogFragment screen image.jpg

现在,如果向下滚动 LazyColumn 列表,那么一切都会正常工作,但如果向上滚动 LazyColumn 列表,则底部工作表对话框将滚动,而不是 LazyColumn 列表。

如何在 BottomSheetDialogFragment 中正确实现 LazyColumn?

当我们使用 XML RecyclerView 列表时,要解决此问题,我们必须使用 NestedScrollView 包装 RecyclerView 列表,如此处描述,但是如何使用 Jetpack Compose 修复它?

android-jetpack-compose android-bottomsheetdialog bottomsheetdialogfragment android-jetpack-compose-list lazycolumn
2个回答
2
投票

您可以在 compose 1.2.0 上使用新的 rememberNestedScrollInteropConnection(),这将允许 compose 中断 View 的滚动并启用嵌套滚动。

在你的情况下会是

setContent {

            Column(modifier = Modifier.nestedScroll(rememberNestedScrollInteropConnection()), horizontalAlignment = Alignment.CenterHorizontally) {

                Text("Header", color = Color.Black)

                LazyColumn(
                    Modifier
                        .weight(1f)
                        .fillMaxWidth()) {
                    items(100) {
                        Text("Item $it", Modifier.fillMaxWidth(), Color.Black)
                    }
                }
            }
        }  

0
投票

您应该使用

BottomSheetScaffold
并将
sheetContent
设置为底部工作表内容。不要使用 BottomSheetDialogFragment。

这是 BottomSheetScaffold 基本结构的示例:

    val scaffoldState = rememberBottomSheetScaffoldState(
        bottomSheetState = rememberBottomSheetState(BottomSheetValue.Expanded)
    )

    BottomSheetScaffold(
        modifier = Modifier.navigationBarsPadding(),
        scaffoldState = scaffoldState,
        topBar = {
            // Your topBar
        },
        sheetShape = BottomSheetShape,
        sheetPeekHeight = MaterialTheme.spacing.large,
        sheetContent = {
            // Your sheet content
        }
    ) { innerPadding ->
      // You content
    }

© www.soinside.com 2019 - 2024. All rights reserved.