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

时间:2021-05-27 18:12:32

标签: android android-jetpack-compose

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用 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
        }
    }
}

然后将 nestedScroll 应用到 Scaffold:

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])
                )
            }
        }
    }
)

enter image description here