You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose中LazyVerticalGrid搭配bottomBar显示异常问题

解决Scaffold中LazyVerticalGrid底部内容被BottomNavigation遮挡的问题

问题原因

Scaffold组件的content区域会自动计算出避开topBar和bottomBar的内边距(通过lambda参数返回PaddingValues),如果不将这个内边距应用到内部的滚动组件上,底部的列表项就会被BottomNavigation遮挡。

修复步骤

1. 传递Scaffold的内边距给NavHost

修改主布局代码,把Scaffold返回的innerPadding传递给FoodstuffNavHost:

val navController = rememberNavController()
Scaffold(
    topBar = { HomeAppBar(navController) },
    bottomBar = { BottomNavigation(navController = navController) }
) { innerPadding ->
    FoodstuffNavHost(navController = navController, innerPadding = innerPadding)
}

2. 在NavHost中传递内边距给目标页面

更新FoodstuffNavHost,将内边距传递给FoodstuffList页面:

@Composable
fun FoodstuffNavHost(navController: NavHostController, innerPadding: PaddingValues) {
    NavHost(navController = navController, startDestination = "foodstuffList") {
        composable("foodstuffList") {
            FoodstuffList(innerPadding = innerPadding)
        }
        // 其他路由配置...
    }
}

3. 给LazyVerticalGrid应用内边距

有两种方式可以实现:

方式一:合并到LazyVerticalGrid的contentPadding
直接把Scaffold的内边距和原有水平内边距合并,确保垂直方向避开导航栏:

@Composable
fun FoodstuffList(innerPadding: PaddingValues) {
    LazyVerticalGrid(
        columns = GridCells.Fixed(3),
        contentPadding = PaddingValues(
            horizontal = dimensionResource(id = R.dimen.horizontal_padding),
            top = innerPadding.calculateTopPadding(),
            bottom = innerPadding.calculateBottomPadding()
        ),
        horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.h_space_between_items)),
        verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.h_space_between_items)),
    ) {
        items(Sample.articles + Sample.articles) { article ->
            SingleFoodstuffUI.UI(foodstuff = article)
        }
    }
}

方式二:用Box包裹并设置padding
更简单的方式是给LazyVerticalGrid套一层Box,直接应用Scaffold的内边距:

@Composable
fun FoodstuffList(innerPadding: PaddingValues) {
    Box(modifier = Modifier.padding(innerPadding)) {
        LazyVerticalGrid(
            columns = GridCells.Fixed(3),
            contentPadding = PaddingValues(horizontal = dimensionResource(id = R.dimen.horizontal_padding)),
            horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.h_space_between_items)),
            verticalArrangement = Arrangement.spacedBy(dimensionResource(id = R.dimen.h_space_between_items)),
        ) {
            items(Sample.articles + Sample.articles) { article ->
                SingleFoodstuffUI.UI(foodstuff = article)
            }
        }
    }
}

原理说明

Scaffold返回的PaddingValues包含了topBar的高度(top padding)和bottomBar的高度(bottom padding),应用这个内边距后,LazyVerticalGrid的滚动区域会自动避开顶部导航栏和底部导航栏的位置,底部的列表项就能正常显示了。

内容的提问来源于stack exchange,提问作者Xavier Soh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:45:40