Showing posts with label ViewPager. Show all posts
Showing posts with label ViewPager. Show all posts

Android TabLayout with ViewPager2 Using Java: Complete Tutorial

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:

  • appcompat provides the AppCompat Toolbar.
  • fragment provides AndroidX Fragment support.
  • viewpager2 provides ViewPager2 and FragmentStateAdapter.
  • material provides 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 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.