How to implement a TabLayout in Android using ViewPager and Fragments

In this article, we will learn about how to add TabLayout with ViewPager in an app. TabLayout provides a horizontal layout to display tabs. If TabLayout is used then along with it, Fragment is also used, because fragments are light weight and the app can have more functionality on a single screen if more fragments are added. Whenever the user clicks on the tab it will lead to the transaction of one Fragment to another. ViewPager is used to swipe between the tabs. WhatsApp, Facebook, etc are a very good example of TabLayout with ViewPager. This is how a TabLayout looks like.

Approach:

  1. Create a AlgorithmFragment by right click on java package,
    select new -> fragment -> select Fragment(Blank).
  2. Follow above step for CourseFragment and LoginFragment.
  3. Now add the following code in AlgorithmFragment.xml file. Here a TextView is added in the layout.
  4. Now add the following code in CourseFragment.xml file. Here a textView is added in the layout.
  5. Now add the following code in LoginFragment.xml file. Here a textView is added in the layout.
  6. Now Create a Adapter for our ViewPager by extending FragmentPagerAdapter class. In this class we will overide three methods getItem(), getCount() and getPageTitle(). getItem method gives the fragment with respect to the position, getCount method gives total number of fragments present and getPageTitle method gives the title of the fragment.
  7. Add the following code in MainActivity.java file. In this file we setup our adapter and attach our TabLayout with ViewPager.

    AlgorithmFragment.xml

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".AlgorithmFragment">
      
        <TextView
            android:textColor="@color/colorPrimary"
            android:textSize="30sp"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Learn Algorithm\nVisit GFG" />
      
    </FrameLayout>

    chevron_right

    
    

    CourseFragment.xml

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".CourseFragment">
      
        <TextView
            android:textColor="@color/colorPrimary"
            android:textSize="30sp"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Select Course by GFG" />
      
    </FrameLayout>

    chevron_right

    
    

    LoginFragment.xml

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".LoginFragment">
      
        <TextView
            android:textColor="@color/colorPrimary"
            android:textSize="30sp"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="GFG Login Portal" />
      
    </FrameLayout>

    chevron_right

    
    

    ViewPagerAdapter.java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package org.geeksforgeeks.gfgtablayout;
      
    import androidx.annotation.NonNull;
    import androidx.fragment.app.Fragment;
    import androidx.fragment.app.FragmentManager;
    import androidx.fragment.app.FragmentPagerAdapter;
      
    public class ViewPagerAdapter
     extends FragmentPagerAdapter {
      
        public ViewPagerAdapter(
    @NonNull FragmentManager fm)
        {
            super(fm);
        }
      
        @NonNull
        @Override
        public Fragment getItem(int position)
        {
            Fragment fragment = null;
            if (position == 0)
                fragment = new AlgorithmFragment();
            else if (position == 1)
                fragment = new CourseFragment();
            else if (position == 2)
                fragment = new LoginFragment();
      
            return fragment;
        }
      
        @Override
        public int getCount()
        {
            return 3;
        }
      
        @Override
        public CharSequence getPageTitle(int position)
        {
            String title = null;
            if (position == 0)
                title = "Algorithm";
            else if (position == 1)
                title = "Courses";
            else if (position == 2)
                title = "Login";
            return title;
        }
    }

    chevron_right

    
    

    MainActivity.java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    package org.geeksforgeeks.gfgtablayout;
      
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.viewpager.widget.ViewPager;
    import android.os.Bundle;
    import android.widget.Toolbar;
      
    import com.google.android.material.tabs.TabLayout;
      
    public class MainActivity
     extends AppCompatActivity {
        TabLayout tabLayout;
        ViewPager viewPager;
        ViewPagerAdapter viewPagerAdapter;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            viewPager = findViewById(R.id.view_pager);
            tabLayout = findViewById(R.id.tabs);
      
            viewPagerAdapter = new ViewPagerAdapter(
                getSupportFragmentManager());
            viewPager.setAdapter(viewPagerAdapter);
      
            // It is used to join TabLayout with ViewPager.
            tabLayout.setupWithViewPager(viewPager);
        }
    }

    chevron_right

    
    

Output:

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.