How to implement a TabLayout in Android using ViewPager and Fragments - GeeksforGeeks

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:
Create a AlgorithmFragment by right click on java package,select new -> fragment -> select Fragment(Blank).Follow above step for CourseFragment and LoginFragment.Now add the following code in AlgorithmFragment.xml file. Here a TextView is added in the layout.Now add the following code in CourseFragment.xml file. Here a textView is added in the layout.Now add the following code in LoginFragment.xml file. Here a textView is added in the layout.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.Add the following code in MainActivity.java file. In this file we setup our adapter and attach our TabLayout with ViewPager.AlgorithmFragment.xmlCourseFragment.xmlLoginFragment.xmlViewPagerAdapter.javaMainActivity.javaAlgorithmFragment.xml<?xml version="1.0" encoding="utf-8"?><FrameLayout    xmlns:android="http://schemas.android.com/apk/res/android"    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:android="http://schemas.android.com/apk/res/android"    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:android="http://schemas.android.com/apk/res/android"    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.javapackage 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.javapackage 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);    }}
Create a AlgorithmFragment by right click on java package,select new -> fragment -> select Fragment(Blank).
Follow above step for CourseFragment and LoginFragment.
Now add the following code in AlgorithmFragment.xml file. Here a TextView is added in the layout.
Now add the following code in CourseFragment.xml file. Here a textView is added in the layout.
Now add the following code in LoginFragment.xml file. Here a textView is added in the layout.
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.
Add the following code in MainActivity.java file. In this file we setup our adapter and attach our TabLayout with ViewPager.AlgorithmFragment.xmlCourseFragment.xmlLoginFragment.xmlViewPagerAdapter.javaMainActivity.javaAlgorithmFragment.xml<?xml version="1.0" encoding="utf-8"?><FrameLayout    xmlns:android="http://schemas.android.com/apk/res/android"    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:android="http://schemas.android.com/apk/res/android"    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:android="http://schemas.android.com/apk/res/android"    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.javapackage 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.javapackage 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);    }}
AlgorithmFragment.xml
CourseFragment.xml
LoginFragment.xml
ViewPagerAdapter.java
MainActivity.java
<?xml version="1.0" encoding="utf-8"?><FrameLayout    xmlns:android="http://schemas.android.com/apk/res/android"    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>
<?xml version="1.0" encoding="utf-8"?><FrameLayout    xmlns:android="http://schemas.android.com/apk/res/android"    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>
<?xml version="1.0" encoding="utf-8"?><FrameLayout    xmlns:android="http://schemas.android.com/apk/res/android"    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>
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;    }}
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:
android
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
How to set fixed width for <td> in a table ?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples