How to add multiple items to Accompanist HorizontalPager?

1k Views Asked by At

When I create

HorizontalPager(count = 3) {
   page  -> ComposableName()
}

It just shows same composable multiple times, i can't add few pages and if I try to

HorizontalPager(count = 3) {
   Image()
   Image()
   Image()
}

elements are just stacked on top of each other and also 3 times.

Is there any way to make smth like

LazyColumn()
{
item {}
item {}
item {}
}

If not what's the simplest solution?

2

There are 2 best solutions below

2
On BEST ANSWER

In the content block of HorizontalPager you get index of the page that should be displayed. So you can do something like this:

HorizontalPager(count = 3) { index ->
    if (index == 0) {
        Image0()
    } else if (index == 1) {
        Image1()
    }
    ...
}
0
On

The way to make it works is:

val itemPager = listOf(Image1: String, Image2: String, Image3: String )

val pagerState = rememberPagerState()
    
HorizontalPager(count = itemPager.size, state = pagerState) { currentPage -> 
     
    Image(currentPage)
}


@Composable
fun Image(page: String) {
     Async...(page)
}

In the example, I used Coil. You can use what you want,