Search code examples
android-viewpagerandroid-jetpack-composeandroid-viewpager2

How to create different contents using Pager in Jetpack Compose?


I want to develop an onboarding flow having different contents using Pager in Jetpack Compose. Because I want for a user to put her different values.

Ex)

  • page1: She will input her name using a textfield.
  • page2: She will input her sex using a dropdown menu.
  • page3: She will read my app's service term.

I mean there screens have different contents.

When I read the doc, we can see the content inside have alike contents like below.

val pagerState = rememberPagerState()

HorizontalPager(pageCount = 10, state = pagerState) { page ->
    // page content
    Text(
        text = "Page: $page",
    )
}

How can I set different contents using pager?

Should I use when block and a pagerState.scrollToPage method?

Please teach me how to write the code.


Solution

  • As you can see in the documentation and in the code, you're getting page number through lambda.

    You'll have to add if or when statement and show the content based on page number. It'll be something like this :

    val pagerState = rememberPagerState()
    
    HorizontalPager(pageCount = 10, state = pagerState) { page ->
    
        when(page){
           
            0 -> {
                InputName()
            }
    
            1 -> {
                GenderSelection()
            }
    
            2 -> {
                TermsOfService()
            }
    
        }
    
    }
    

    Here InputName(), GenderSelection(), TermsOfService() are all different @Composable functions/screens.