The Wayback Machine - https://web.archive.org/web/20240914151142/https://www.geeksforgeeks.org/viewpager-using-fragments-in-android-with-example/
Open In App

ViewPager Using Fragments in Android with Example

Last Updated : 19 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

ViewPager is a layout manager that allows the user to flip left and right through pages of data. It is mostly found in apps like Youtube, Snapchat where the user shifts right – left to switch to a screen. Instead of using activities fragments are used. It is also used to guide the user through the app when the user launches the app for the first time. 

ViewPager Using Fragments in Android

Steps for implementing viewpager: 

  1. Adding the ViewPager widget to the XML layout (usually the main_layout).
  2. Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class.

An adapter populates the pages inside the Viewpager. PagerAdapter is the base class which is extended by FragmentPagerAdapter and FragmentStatePagerAdapter. Let’s see a quick difference between the two classes.

Difference between  FragmentPagerAdapter and FragmentStatePagerAdapter:

  • FragmentStatePagerAdapter: Keeps in memory only the current fragment displayed on the screen. This is memory efficient and should be used in applications with dynamic fragments. (where the number of fragments is not fixed.).
  • FragmentPagerAdapter: This adapter should be used when the number of fragments is fixed. An application that has 3 tabs which won’t change during the runtime of the application. This tutorial will be using FragmentPagerAdapter.

Following is the structure of the ViewPagerAdapter Class:

Java
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> fragments = new ArrayList<>();
    private final List<String> fragmentTitle = new ArrayList<>();

    public ViewPagerAdapter(@NonNull FragmentManager fm)
    {
        super(fm);
    }

    public void add(Fragment fragment, String title)
    {
        fragments.add(fragment);
        fragmentTitle.add(title);
    }

    @NonNull @Override public Fragment getItem(int position)
    {
        return fragments.get(position);
    }

    @Override public int getCount()
    {
        return fragments.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position)
    {
        return fragmentTitle.get(position);
    }
}

 
Method Description: 

  • getCount(): This method returns the number of fragments to display.  (Required to Override)
  • getItem(int pos): Returns the fragment at the pos index.  (Required to override)
  • ViewPagerAdapter(@NonNull FragmentManager FM): (required) The ViewPager Adapter needs to have a parameterized constructor that accepts the FragmentManager instance. Which is responsible for managing the fragments. A FragmentManager manages Fragments in Android, specifically, it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments.
  • getPageTitle(int pos): (optional) Similar to getItem() this methods returns the title of the page at index pos.
  • add(Fragment fragment, String title): This method is responsible for populating the fragments and fragmentTitle lists. which hold the fragments and titles respectively.

Example

A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.  

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Initially, the project directory should look like this. 

Step 2: Working with the activity_main.xml file 

12

The three widgets AppBarLayout used to host the TabLayout which is responsible for displaying the page titles. ViewPager layout which will house the different fragments. The below Image explains the important parameters to set to get the app working as intended. 

12-

In the TabLayout we need to add the tabmode = “fixed” parameter which tells the android system that will have a fixed number of tabs in our application. Add the following code to the “activity_main.xml” file.  

XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
    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">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:tabGravity="fill"
            app:tabMode="fixed" />

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Step 3: Create Fragments

Now we need to design out pages that are fragmented. For this tutorial, we will be using three Pages (fragments). Add three blank fragments to the project. The project Structure should look like this.  

Below is the code for the Page1.java, Page2.java, and Page3.java file respectively. 

Java
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 Page1 extends Fragment {

    public Page1() {
        // required empty public constructor.
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_page1, container, false);
    }
}
Java
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 Page2 extends Fragment {

    public Page2() {
        // required empty public constructor.
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_page2, container, false);
    }
}
Java
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 Page3 extends Fragment {
    
    public Page3() {
        // required empty public constructor.
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_page3, container, false);
    }
}

Method Description:  

  • Page1(): Default Constructure.
  • onCreateView( onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState): This method is responsible for inflating (parsing) the respective XML file and return the view which is added to the ViewPager adapter.
  • onCreate(Bundle SaveInstanceState): This methods is similar to activities OnCreate() method.

Designing the Page XML Files. All the fragments XML layouts have the same designs. We have a TextView at the center displaying the name of the respective page, the root container used here is FrameLayout whose background is set to  #0F9D58

Below is the code for the fragment_page1.xml file: 

14

Code: 

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"
    android:background="#0F9D58"
    tools:context=".Page1">
    
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Page 1"
        android:textColor="@color/white"
        android:textSize="60sp"
        android:textStyle="bold" />
</FrameLayout>

 Below is the code for the fragment_page2.xml file: 

15

Code:  

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"
    android:background="#0F9D58"
    tools:context=".Page2">
    
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Page 2"
        android:textColor="@color/white"
        android:textSize="60sp"
        android:textStyle="bold" />
</FrameLayout>

Below is the code for the fragment_page3.xml file: 

16

Code: 

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"
    android:background="#0F9D58"
    tools:context=".Page3">
    
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Page 3"
        android:textColor="@color/white"
        android:textSize="60sp"
        android:textStyle="bold" />
</FrameLayout>

Step 4: Creating the ViewPager Adapter 

Add a java class named ViewPagerAdapter to the project structure. The project structure would look like this. 

Below is the code for the ViewPagerAdapter.java file:  

Java
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends FragmentPagerAdapter {
    
    private final List<Fragment> fragments = new ArrayList<>();
    private final List<String> fragmentTitle = new ArrayList<>();

    public ViewPagerAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }
    
    public void add(Fragment fragment, String title) {
        fragments.add(fragment);
        fragmentTitle.add(title);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
    
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentTitle.get(position);
    }
}

Step 5: Working with the MainActivity.java file

In the MainActivity, we need to perform the following steps.  

  1. Initialize the ViewPager, TabLayout, and the Adapter.
  2. Add the Pages (fragments ) along with the titles
  3. Link the TabLayout to the Viewpager using the setupWithiewPager method.

Syntax:TabLayout.setupWithiewPager(ViewPager pager).

Description: The tablayout with the viewpager. The titles of each pager now appears on the tablayout. The user can also navigate through the fragments by clicking on the tabs.

Parameter:

Viewpager: Used to display the fragments.

Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {
    
    private ViewPagerAdapter viewPagerAdapter;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.viewpager);

        // setting up the adapter
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        // add the fragments
        viewPagerAdapter.add(new Page1(), "Page 1");
        viewPagerAdapter.add(new Page2(), "Page 2");
        viewPagerAdapter.add(new Page3(), "Page 3");

        // Set the adapter
        viewPager.setAdapter(viewPagerAdapter);

        // The Page (fragment) titles will be displayed in the
        // tabLayout hence we need to  set the page viewer
        // we use the setupWithViewPager().
        tabLayout = findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);
    }
}

Output:  


 Find the code in the following GitHub repo: https://github.com/evilc3/ViewPager


 



Previous Article
Next Article

Similar Reads

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 click
3 min read
Android Image Slider using ViewPager in Kotlin
Image slider is seen in most e-commerce applications that display advertisements on the home screen. This slider displays the advertisement banners which users can slide to view the others. In this article, we will take a look at Implementing the image slider using ViewPager in Android using Kotlin. A sample video is given below to get an idea abou
5 min read
How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
In some Android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On the other hand, it provides a different look to that app. It is also possible to provide a different feel like left and right swipes by using ViewPager. And to implement this topic, a few terms are required such as ViewPager,
8 min read
Image Slider in Android using ViewPager
When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in the Android Apps using the left and right swipes as opposed to clicking on Buttons. Not only does it look more simple and elegant but also provid
4 min read
How to Implement ViewPager with Dotsindicator in Android?
ViewPager in Android is a class that allows the user to flip left and right through pages of data. This class provides the functionality to flip pages in-app. It is a widget found in the support library. What are Dotsindicator? These are dots that help us to see which view is currently opened when we have multiple views. Some of the attributes of t
4 min read
Android ViewPager in Kotlin
ViewPager adds a sleek, swipeable interface that lets users effortlessly navigate between pages, just like flipping through a book. This feature is common in social media apps; for instance, WhatsApp greets you with three intuitive tabs: chats, status, and calls. This makes the app look cool. You've probably noticed it guiding you through an app’s
5 min read
Cube in Scaling Animation with ViewPager in Android
The Android ViewPager has become a very interesting concept among Android apps. It enables users to switch smoothly between fragments which have a common UI and it’s the best way to make your app extraordinary from others. ViewPagers provide visual continuity. They basically keep track of which page is visible and then ask PageAdapter to display th
5 min read
View Binding with Fragments in Android Jetpack
In the Previous article View Binding in Android Jetpack, it's been discussed why acquiring the ViewBinding feature in the Android project provides a lot of benefits. But when it comes to ViewBinding with fragments the scenario changes. Because the lifecycle of the Fragment is different and that of activity is different Here also things go the same
6 min read
How to Implement findViewById in Fragments in Android?
Fragments represent a part of the app's UI which is reusable. Fragments are having its own layout, and lifecycle but must be hosted inside an activity to be visible. The activity becomes easier to modify if it consists of many fragments. A fragment can have multiple instances inside an activity. findViewById finds the view by the given ID. Step By
3 min read
How to Implement onBackPressed() in Fragments in Android?
In Android, the Fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. onBackPressed() is a method that is to be implemented i
3 min read
Introduction to Fragments | Android
Fragment is a piece of an activity that enables a more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pan
5 min read
Data Binding in Android: Activities, Views, and Fragments
Data binding in Android is one of the most effective features for Android developers to bind the UI controls present in the layout with the data resources in the code. This makes the code less complicated and readable thus enhancing the overall maintainability of the application. In this article, I will be explaining what data binding is; how to im
4 min read
How to Communicate Between Fragments in Android?
Nowadays most apps have so many features so for that they use multiple fragments in a single app and communication is one of the important parts of apps for sharing data from one fragment to another because two fragments can't communicate directly. A Fragment represents a portion of any user interface. There can be a number of fragments within one
4 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
RecyclerView using GridLayoutManager in Android With Example
RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. How to use RecyclerView as GridView? While implementing Recycler view in
6 min read
CardView using RecyclerView in Android with Example
RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on the implementation of CardView in RecyclerView. We should know what CardView and RecyclerView mean. CardView: CardView is an extend
9 min read
Dagger 2 Android Example using Retrofit
Dagger 2 Android implementation is easier and it is based on Dependency Injection Architecture. Dependency Injection is a design pattern, which is a concept of Object-Oriented Programming, where we don’t create an object of another class inside a class using the new keyword (for Java). Instead, we supply the needed object from the outside. It is a
6 min read
GridView Using BaseAdapter in Android with Example
Here, we are designing an Android app to demonstrate the use of GridView layout. The GridView layout is a ViewGroup that groups view in a two-dimensional scrolling grid of rows and columns. Items in the grid view are inserted using a ListAdapter. The layout by default is scrollable and we don't need to use ScrollView. An example of GridView is your
7 min read
GridView Using Custom ArrayAdapter in Android with Example
This article will be building an application to demonstrate the use of CustomArrayAdapters in GridView. GridViews are view containers that display views in two-dimensional (rows and columns) they are used in my android applications one simple example would be the gallery app. The adapter connects the UI elements with the data source, It helps popul
9 min read
RecyclerView using ListView in Android With Example
RecyclerView is a more flexible and advanced version of ListView and GridView. RecyclerView is used for providing a limited window to a large data set, which means it is used to display a large amount of data that can be scrolled very efficiently by maintaining a limited number of Views. In RecyclerView we supply data and define how each item looks
6 min read
Drag and Drop using DragLinearLayout in Android with Example
In most of the To-do list apps, we need to create a view such that the user can prioritize his daily tasks according to his priority. For this feature to work he should be able to drag and drop view items. For adding this type of functionality inside our app we have to use DragLinearLayout inside our app. In this article, we will take a look at How
3 min read
How to Add OpenCV library into Android Application using Android Studio?
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries,
3 min read
How to Capture a Screenshot and Screen Recording of an Android Device Using Android Studio?
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps. Whenever we are developing an app and in that device, you don't know how to capture screenshot
2 min read
How to Make a Scientific Calculator Android App using Android Studio?
The calculator is the app that is present on every android device. This app comes pre-installed or we can also install another application from Play Store. It is one of the most used applications for college students for making any calculations. In this article, we will take a look at building a simple scientific calculator app in Android using Kot
13 min read
Star Shower in Android using Android Property Animation
In this article, we are going to create a star shower using android property animation. We will create a slightly more involved animation, animating multiple properties on multiple objects. For this effect, a button click will result in the creation of a star with a random size, which will be added to the background container, just out of view of t
7 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Android Animation using Android Studio
In today's world which is filled with full of imagination and visualizations, there are some areas that are covered with the word animation. When this word will come to anyone’s mind they always create a picture of cartoons and some Disney world shows. As we already know that among kids, animation movies are very popular like Disney world, Doraemon
5 min read
Android Jetpack - WorkManager with Example
WorkManager is an Android Jetpack library that provides a flexible and efficient way to schedule and manage background tasks in your app. It is a powerful and recommended tool for managing background processing in Android applications. With WorkManager, you can schedule asynchronous, deferred, and periodic tasks that need to run even when the app i
5 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Spinner in Android with Example
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using Adapter we ca
4 min read
Article Tags :
Practice Tags :