Skip to content
Related Articles

Related Articles

How to implement a TabLayout in Android using ViewPager and Fragments
  • Difficulty Level : Medium
  • Last Updated : 02 Jul, 2020

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




    <?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>

    CourseFragment.xml




    <?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>

    LoginFragment.xml




    <?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>

    ViewPagerAdapter.java




    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;
        }
    }

    MainActivity.java




    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);
        }
    }

Output:

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!



My Personal Notes arrow_drop_up
Recommended Articles
Page :