Create Tabs using ViewPager , TabLayout and FragmentPagerAdapter in Android

  • 1. Create a new android project
  • 2. Add ViewPager and TabLayout widget to the layout of the activity i.e main_activity.xml
  • 3. Initialize the UI components in MainActivity.java
  • 4. Lets create the fragments to be used as pages for the viewpager.

    We have created three fragments with different background colors.

  • 5. Create an adapter for the viewpager.
    1. Create a class ViewPagerAdapter and extend FragmentPagerAdapter
    Now lets add the methods to implement and the default constructor , and ViewPagerAdapter look like —
    2. Create two List variables to hold the fragments and the page titles(TO be displayed on the tabs)
    Initialize them in the constructor.
    Create a method add Fragments and titles to the list variable.
    3. Override the implemented methods .
    a. getCount() should return the total number of pages to be diplayed i.e. mPages.size() in our case
    b. getItem(int position) returns the fragment to be diplayed at the specified position.
    c. getPageTitle(int position) is used to provide the title of the page at the specified position, we shall use this to name the tabs.
  • 6. Set the adapter to the viewpager

    mViewPager.setAdapter(mAdapter);

  • 7. Link the tablayout to the viewpager

    mTabs.setupWithViewPager(mViewPager);

Leave a Reply

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