如何在Jetpack Compose中创建一个无限的Pager

huangapple go评论51阅读模式
英文:

How to create an endless Pager in Jetpack Compose

问题

Box(
    modifier = Modifier.size(100.dp),
    contentAlignment = Alignment.Center
) {
    val pagerState = rememberPagerState()
    val items = listOf("A", "B", "C")
    androidx.compose.foundation.pager.HorizontalPager(
        state = pagerState,
        pageCount = items.size,
        modifier = Modifier,
        verticalAlignment = Alignment.CenterVertically
    ) { page ->
        Text(
            text = items[page],
            modifier = Modifier
        )
    }
}

在上述代码中,Pager在达到最后一项后停止滚动。然而,我想要Pager在达到最后一项后继续无限滚动。

英文:
    Box(
        modifier = Modifier.size(100.dp),
        contentAlignment = Alignment.Center
    ) {
        val pagerState = rememberPagerState()
        val items = listOf("A", "B", "C")
        androidx.compose.foundation.pager.HorizontalPager(
            state = pagerState,
            pageCount = items.size,
            modifier = Modifier,
            verticalAlignment = Alignment.CenterVertically
        ) { page ->
            Text(
                text = items[page],
                modifier = Modifier
            )
        }
    }

In the above code, the pager stops scrolling after reaching the last item. However, I want the pager to continue scrolling endlessly after reaching the last item.

如何在Jetpack Compose中创建一个无限的Pager

答案1

得分: 8

以下是您要翻译的代码部分:

"You can create it by setting pageCount to Int.MAX_VALUE and getting modulus of current page to get index for your list of items.

@Preview
@Composable
private fun Test() {

val pageCount = Int.MAX_VALUE
val items = listOf("A", "B", "C")
val pagerState = rememberPagerState(
    initialPage = pageCount / 2
)

HorizontalPager(
    modifier = Modifier.fillMaxWidth(),
    pageCount = pageCount,
    state = pagerState
) {
     Text(text = items[it % 3])
}

}"

英文:

You can create it by setting pageCount to Int.MAX_VALUE and getting modulus of current page to get index for your list of items.

@Preview
@Composable
private fun Test() {

    val pageCount = Int.MAX_VALUE
    val items = listOf("A", "B", "C")
    val pagerState = rememberPagerState(
        initialPage = pageCount / 2
    )

    HorizontalPager(
        modifier = Modifier.fillMaxWidth(),
        pageCount = pageCount,
        state = pagerState
    ) {
         Text(text = items[it % 3])
    }
}

huangapple
  • 本文由 发表于 2023年2月16日 14:24:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定