在 Jetpack Compose 上滚动时折叠导航底部栏

Fra*_*cia 8 android android-jetpack-compose

我期待着一种在LazyColumn列表上滚动时实现折叠效果的方法。我一直在检查文档,但没有发现任何相关内容。我该如何实施?

目前,我在BottomNavigation我的内部使用了一个设置Scaffold,我可以将来自脚手架内容 lambda 的内部填充添加到屏幕上。但我没有找到任何类型的可滚动状态或类似的状态。

Gab*_*tti 14

您可以使用nestedScroll修饰符。

就像是:

val bottomBarHeight = 48.dp
val bottomBarHeightPx = with(LocalDensity.current) { bottomBarHeight.roundToPx().toFloat() }
val bottomBarOffsetHeightPx = remember { mutableStateOf(0f) }


// connection to the nested scroll system and listen to the scroll
// happening inside child LazyColumn
val nestedScrollConnection = remember {
    object : NestedScrollConnection {
        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {

            val delta = available.y
            val newOffset = bottomBarOffsetHeightPx.value + delta
            bottomBarOffsetHeightPx.value = newOffset.coerceIn(-bottomBarHeightPx, 0f)

            return Offset.Zero
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其应用nestedScroll到脚手架:

Scaffold(
    Modifier.nestedScroll(nestedScrollConnection),
    scaffoldState = scaffoldState,
    //..
    bottomBar = {
        BottomAppBar(modifier = Modifier
            .height(bottomBarHeight)
            .offset { IntOffset(x = 0, y = -bottomBarOffsetHeightPx.value.roundToInt()) }) {
            IconButton(
                onClick = {
                    coroutineScope.launch { scaffoldState.drawerState.open() }
                }
            ) {
                Icon(Icons.Filled.Menu, contentDescription = "Localized description")
            }
        }
    },

    content = { innerPadding ->
        LazyColumn(contentPadding = innerPadding) {
            items(count = 100) {
                Box(
                    Modifier
                        .fillMaxWidth()
                        .height(50.dp)
                        .background(colors[it % colors.size])
                )
            }
        }
    }
)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我尝试了 TopAppBar,问题是 topAppBar 确实按预期折叠,但在其位置留下了空白,对于 topAppBars 是否有建议的不同方法? (5认同)