Viewpager in Android

In this Article we will discuss about what is viewpager and use of viewpager in android.


The ViewPager is a component in Android that allows swiping between pages of content, such as fragments. It’s part of the Android Support Library, and provides an easy way to create horizontal navigation between pages. The pages are typically fragments that are managed by a PagerAdapter.

ViewPager is an Android widget used to implement swipe-able screens in an application. It allows the user to swipe left or right through pages of data. The ViewPager manages the layout for each page and provides built-in scrolling behavior. It’s typically used in conjunction with a FragmentStatePagerAdapter or FragmentPagerAdapter.


Here is a basic example of using a ViewPager in Android:

  • Add the ViewPager component in your layout XML file:
    android:layout_height="match_parent" />
  • Create a Fragment class for each page you want to display in your ViewPager:
public static class PageFragment extends Fragment {
    public static PageFragment newInstance(int page) {
        PageFragment fragment = new PageFragment();
        Bundle args = new Bundle();
        args.putInt("page", page);
        return fragment;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page, container, false);
        TextView textView = view.findViewById(;
        int page = getArguments().getInt("page");
        textView.setText("Page " + page);
        return view;
  • Create a FragmentPagerAdapter or FragmentStatePagerAdapter to provide the pages to the ViewPager:
public class PageAdapter extends FragmentPagerAdapter {
    private int numOfPages;
    public PageAdapter(FragmentManager fm, int numOfPages) {
        this.numOfPages = numOfPages;
    public Fragment getItem(int position) {
        return PageFragment.newInstance(position + 1);
    public int getCount() {
        return numOfPages;
  • In your activity class, set the adapter for the ViewPager and specify the number of pages:
public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        ViewPager viewPager = findViewById(;
        PageAdapter adapter = new PageAdapter(getSupportFragmentManager(), 3);

This is just a basic example. You can customize the ViewPager and the adapter as needed for your specific use case.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories