The ViewPager is a view that we can add to our layout so we can swipe vertically or horizontally across the screen to flip through multiple pages.
The ViewPager is a view that we can add to our layout so we can swipe vertically or horizontally across the screen to flip through multiple pages.
Before we begin, add the dependency for the ViewPager. Go to the app level build gradle file and add the implementation.
App Grade File
For the latest version, visit the android developer website.
https://developer.android.com/jetpack/androidx/releases/viewpager2#androidx-deps
Creating the Fragment for Each Page
Rename the fragment and click finish.
Replace the TextView with a button and add the constraints so it will be in the center of the screen.
Now, go to the Fragment’s class file and remove all the unnecessary code except the constructor and the onCreateView() method.
Then create a reference for the button in the onCreateView() method.
Define a String variable call title and add a parameter to the constructor to accept a string. Then set the value of the title variable to the string that is coming in.
Lastly, call the setText() method from the button object and pass in the title.
Now, we have our page.
Creating the ViewPager
Then in the Attribute pane, give it an id.
Go to the fragment or activity that is using the layout with the ViewPager and declare a reference for it.
Creating and Attaching the Adapter
To create the Adapter, define a class and have it extend FragmentStateAdapter.
Then hover and click on the class definition. You will see a red lightbulb icon. Click on it and select the “Implement methods” option.
Repeat the same step and select the “Create constructor matching super” option.
You will see a few choices that you can make. Depending on where you are going to declare and initialize the adapter, you should choose what is best for you. If you do not know, select all the options by pressing shift and clicking on the last item and then click OK.
In the createFragment() method, return the fragment that we created earlier for the pages.
And in the getItemCount() method, return 10. This will tell our ViewPager that we have 10 pages.
Lastly, add the adapter to the ViewPager by calling setAdapter() and pass in the adapter object.
If we run the app, we will see that we can flip through our pages by swiping left or right.
Display Different Data
If you notice, all our pages are displaying the same text. To change this, we need to create some data and modify the adapter.
Declare a String array and then populate it with some data.
In the getItemCount() method of the adapter, replace 10 with the length of the array.
In the createFragment() method, instead of using a hard coded value when instantiating the fragment, pass in the data.
If we run the app again, each page will display a different text.