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

Jetpack Compose中rememberPagerState报错,无法实现滑动切换板块

解决Jetpack Compose中rememberPagerState参数错误问题

你的报错是因为调用rememberPagerState时传入了不存在的pageCount命名参数,当前版本的rememberPagerState没有这个参数重载,正确的用法有两种:

方案1:在HorizontalPager中指定pageCount

rememberPagerState只需要传入初始页码(可选,默认0),然后在HorizontalPager组件中直接设置总页数:

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HomeScreen() {
    val sections = listOf("Overview", "Indices", "Stocks")
    // 只传初始页,或者不传使用默认值0
    val pagerState = rememberPagerState(initialPage = 0)

    Column {
        homeSectionBar(
            homeSelectedSection = sections[pagerState.currentPage],
            onSectionSelected = { section ->
                pagerState.animateScrollToPage(sections.indexOf(section))
            },
        )

        // 在HorizontalPager中添加pageCount参数
        HorizontalPager(
            state = pagerState,
            pageCount = sections.size
        ) { page ->
            when (sections[page]) {
                "Overview" -> OverviewScreen()
                "Indices" -> IndexScreen()
                "Stocks" -> StockScreen()
            }
        }
    }
}

方案2:使用rememberPagerState的pageCount lambda重载

如果你想在rememberPagerState中指定总页数,可以通过第三个lambda参数传入:

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HomeScreen() {
    val sections = listOf("Overview", "Indices", "Stocks")
    // 通过lambda提供总页数
    val pagerState = rememberPagerState(
        initialPage = 0,
        pageCount = { sections.size }
    )

    Column {
        homeSectionBar(
            homeSelectedSection = sections[pagerState.currentPage],
            onSectionSelected = { section ->
                pagerState.animateScrollToPage(sections.indexOf(section))
            },
        )

        // 此时HorizontalPager无需再传pageCount
        HorizontalPager(state = pagerState) { page ->
            when (sections[page]) {
                "Overview" -> OverviewScreen()
                "Indices" -> IndexScreen()
                "Stocks" -> StockScreen()
            }
        }
    }
}

额外注意事项

你的代码中存在两处导入乱码,需要修正:

  • 将import androidx.compose.foundatyour textion.pager.HorizontalPager改为import androidx.compose.foundation.pager.HorizontalPager
  • 将androyour textidx.compose.runtime.getValue改为import androidx.compose.runtime.getValue

内容的提问来源于stack exchange,提问作者Sunaan S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:15:04