Tabs with ViewPager2 in Android Using Java: Complete Tutorial
Tabs make it easy to organize related content into separate sections of an Android app. Many applications use tabs to let users switch between different screens without navigating away from the current page. In this tutorial, you will learn how to implement tabs with ViewPager2 in Android using Java, Material TabLayout, and fragments. We will build a complete example with three tabs: Chat, Contact, and Call. You will learn how to configure the dependencies, create the XML layouts, implement the fragments, and connect TabLayout with ViewPager2.
What are TabLayout and ViewPager2 in Android?
TabLayout and ViewPager2 are Android components that work together to create a tab-based navigation interface.
- TabLayout: Displays a row of tabs. Users can tap a tab to select a particular section.
- ViewPager2: Displays pages and allows users to swipe horizontally between them.
- Fragment: Represents the content displayed inside each page.
- TabLayoutMediator: Connects TabLayout with ViewPager2 and keeps their selected positions synchronized.
For example, suppose your application has three sections: Chat, Contact, and Call. You can create three fragments and display them using ViewPager2. TabLayoutMediator connects the tabs to the corresponding pages.
When users tap Contact, ViewPager2 displays the Contact fragment. When they swipe to Call, the Call tab becomes selected automatically.
This approach is useful when an application contains a small number of related sections that users need to access quickly.
Expected output
After completing this tutorial, your screen will contain:
- A toolbar displaying the application title.
- Three tabs: Chat, Contact, and Call.
- A content area displaying the selected fragment.
- Horizontal swipe navigation between the three fragments.
- Automatic tab selection when users swipe between pages.
For demonstration, each fragment displays a centered text label. You can replace these labels with a RecyclerView, contact list, chat messages, or any other application content.
Add the required dependencies
First, open your app-level build.gradle file and add the following dependencies inside the dependencies block:
dependencies {
implementation 'androidx.appcompat:appcompat:1.7.0'
implementation 'androidx.fragment:fragment:1.8.5'
implementation 'androidx.viewpager2:viewpager2:1.1.0'
implementation 'com.google.android.material:material:1.12.0'
}
These dependencies provide the components required for this example:
appcompatprovides the AppCompat Toolbar.fragmentprovides AndroidX Fragment support.viewpager2provides ViewPager2 and FragmentStateAdapter.materialprovides Material TabLayout and TabLayoutMediator.
After adding the dependencies, sync your Gradle project. If your project already uses compatible versions of these libraries, keep the existing versions instead of adding duplicate dependencies.
These are example dependency versions. Check your project's compile SDK, Android Gradle Plugin, and dependency compatibility before upgrading library versions.
Create fragment_gallery.xml
The host layout contains the toolbar, TabLayout, and ViewPager2. We will use a vertical LinearLayout to arrange these components.
Create a file named fragment_gallery.xml inside your app's res/layout directory:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#3F51B5"
app:title="My Application"
app:titleTextColor="#FFFFFF" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/mytab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3F51B5"
app:tabIndicatorColor="#FFFFFF"
app:tabSelectedTextColor="#FFFFFF"
app:tabTextColor="#D9D9D9" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
Understanding the layout components
- AppBarLayout: Groups the toolbar and TabLayout in the application header.
- Toolbar: Displays the application title.
- TabLayout: Displays the Chat, Contact, and Call tabs. We will populate these tabs using TabLayoutMediator.
- ViewPager2: Displays the fragment pages and supports horizontal swipe navigation.
Notice that ViewPager2 uses layout_height="0dp" with layout_weight="1". This allows it to occupy the remaining available screen space below the AppBarLayout.
Implement GalleryFragment.java
Now create the GalleryFragment.java class. This fragment acts as the host for TabLayout and ViewPager2.
It initializes both components, creates the adapter, and connects the tabs with the pages using TabLayoutMediator.
package com.example.mynavigation.ui.gallery;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.example.mynavigation.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class GalleryFragment extends Fragment {
private static final String[] TAB_TITLES = {
"Chat",
"Contact",
"Call"
};
private TabLayoutMediator tabLayoutMediator;
@Nullable
@Override
public View onCreateView(
@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(
R.layout.fragment_gallery,
container,
false
);
}
@Override
public void onViewCreated(
@NonNull View view,
@Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TabLayout tabs = view.findViewById(R.id.mytab);
ViewPager2 viewPager = view.findViewById(R.id.viewpager);
GalleryPagerAdapter adapter =
new GalleryPagerAdapter(this);
viewPager.setAdapter(adapter);
tabLayoutMediator = new TabLayoutMediator(
tabs,
viewPager,
(tab, position) ->
tab.setText(TAB_TITLES[position])
);
tabLayoutMediator.attach();
}
@Override
public void onDestroyView() {
if (tabLayoutMediator != null) {
tabLayoutMediator.detach();
tabLayoutMediator = null;
}
super.onDestroyView();
}
}
Understanding GalleryFragment.java
1. onCreateView()
The onCreateView() method inflates fragment_gallery.xml and returns the root view of the fragment.
2. onViewCreated()
This method runs after the fragment's view has been created. We use findViewById() to get the TabLayout and ViewPager2 references.
Next, we create the adapter and assign it to ViewPager2.
3. TabLayoutMediator
TabLayoutMediator connects TabLayout with ViewPager2. Its configuration callback receives the tab and its position. We use the position to assign the appropriate tab title.
The attach() method activates the connection. After this, tapping a tab changes the displayed page, and swiping between pages updates the selected tab.
4. onDestroyView()
We detach TabLayoutMediator when the fragment's view is destroyed. This helps avoid retaining references to the old view hierarchy when the fragment view is recreated.
Create the ViewPager2 adapter
ViewPager2 uses RecyclerView.Adapter-based architecture. When working with fragments, AndroidX provides FragmentStateAdapter.
Create a Java class named GalleryPagerAdapter.java:
package com.example.mynavigation.ui.gallery;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.example.mynavigation.CallFragment;
import com.example.mynavigation.ChatFragment;
import com.example.mynavigation.ContactFragment;
public class GalleryPagerAdapter extends FragmentStateAdapter {
public GalleryPagerAdapter(@NonNull Fragment fragment) {
super(fragment);
}
@NonNull
@Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new ChatFragment();
case 1:
return new ContactFragment();
case 2:
return new CallFragment();
default:
throw new IllegalArgumentException(
"Invalid tab position: " + position
);
}
}
@Override
public int getItemCount() {
return 3;
}
}
Understanding FragmentStateAdapter
- FragmentStateAdapter: Manages fragments displayed by ViewPager2.
- createFragment(int position): Creates and returns the fragment for the requested position.
- getItemCount(): Returns the total number of pages.
In this example, position 0 displays ChatFragment, position 1 displays ContactFragment, and position 2 displays CallFragment.
Unlike the older FragmentPagerAdapter approach, FragmentStateAdapter is designed for ViewPager2 and manages fragment state as pages move in and out of the active area.
Create Chat, Contact, and Call fragments
Each tab needs its own fragment. These fragments are responsible for displaying the content of their respective pages.
1. ChatFragment.java
package com.example.mynavigation;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class ChatFragment extends Fragment {
@Nullable
@Override
public View onCreateView(
@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(
R.layout.chat,
container,
false
);
}
}
2. ContactFragment.java
package com.example.mynavigation;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class ContactFragment extends Fragment {
@Nullable
@Override
public View onCreateView(
@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(
R.layout.contact,
container,
false
);
}
}
3. CallFragment.java
package com.example.mynavigation;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class CallFragment extends Fragment {
@Nullable
@Override
public View onCreateView(
@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(
R.layout.call,
container,
false
);
}
}
All three fragments follow the same structure. The only difference is the layout resource each fragment inflates.
In a real application, you can add RecyclerView, database operations, API calls, click listeners, and other UI components inside these fragments.
Create the tab layouts
Each fragment needs its own XML layout. For this demonstration, we will display a centered TextView in each tab.
1. chat.xml
Create chat.xml inside res/layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Chat"
android:textSize="30sp" />
</FrameLayout>
2. contact.xml
Create contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Contact"
android:textSize="30sp" />
</FrameLayout>
3. call.xml
Create call.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Call"
android:textSize="30sp" />
</FrameLayout>
The layout_gravity="center" attribute positions the TextView in the center of the FrameLayout. The gravity="center" attribute centers the text inside the TextView.
You can replace these simple layouts with your actual application screens whenever you are ready.
Frequently asked questions
What is the difference between TabLayout and ViewPager2?
TabLayout displays the tabs and allows users to select a section. ViewPager2 displays the corresponding pages and supports swipe navigation. TabLayoutMediator connects both components.
What is TabLayoutMediator in Android?
TabLayoutMediator is a Material Components class that connects TabLayout with ViewPager2. It synchronizes tab selection and page navigation. You configure the tab titles through its callback and call attach() to activate the connection.
What is the difference between ViewPager and ViewPager2?
ViewPager is the older AndroidX paging component, while ViewPager2 is its newer replacement. ViewPager2 uses RecyclerView-based architecture, supports vertical orientation, supports right-to-left layouts, and provides improved fragment handling through FragmentStateAdapter.
Which adapter is used with ViewPager2 and fragments?
Use FragmentStateAdapter when displaying fragments with ViewPager2. It provides methods such as createFragment() and getItemCount() to manage the pages.
Can I add more tabs to ViewPager2?
Yes. Add another fragment to the adapter's createFragment() method, increase the value returned by getItemCount(), and add the corresponding title to the tab title array.
Why are my tabs not synchronized with ViewPager2?
Check that you have created TabLayoutMediator with the correct TabLayout and ViewPager2 instances. Also make sure that you call attach() after setting the ViewPager2 adapter.
Can I use RecyclerView inside a ViewPager2 fragment?
Yes. Each fragment can contain its own RecyclerView, which is useful for displaying chat messages, contacts, call history, or other lists.
Can ViewPager2 be used inside another fragment?
Yes. When ViewPager2 is hosted inside a fragment, use that host fragment when creating FragmentStateAdapter, as shown in this tutorial. This allows the adapter to use the host fragment's child FragmentManager.
Conclusion
You have now learned how to create a tab-based Android interface using Java, Material TabLayout, ViewPager2, and fragments.
Here is a quick recap of the components:
- TabLayout: Displays the navigation tabs.
- ViewPager2: Displays pages and handles swipe navigation.
- FragmentStateAdapter: Creates and manages fragment pages.
- TabLayoutMediator: Connects the tabs and pages.
- Fragments: Hold the content of individual tabs.
The most important part of this implementation is TabLayoutMediator. It keeps the selected tab and the displayed ViewPager2 page synchronized.
Try adding a fourth tab, replacing the TextViews with RecyclerViews, and loading actual application data. This will help you understand how to use the same structure in a real Android project.