Android ViewPager

Android ViewPager With Fragment

Android ViewPager can be defined as below –

"Android ViewPager allows the user to flip left and right through pages of data."

Android ViewPager widget is found in the support library and allows the user to swipe left or right to see an completely new screen. We use PagerAdapter to create pages and provide it to the ViewPager.

At first, we will create android application. Then, we will use VewPager in this application.

Follow steps below to create new project. Please ignore the steps if you've already created a new application.

 

 

 

 

S. No. Steps
1 Open Android Studio.
2 Click on Start a new Android Studio Project Write application name as ViewPager. Then, click next button.
3 Select minimum SDK you need. However, we have selected 14 as minimum SDK. Then, click next button.
4 Then, select Empty Activity => click next => click finish.
5 If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit tutorial  to Create a New Project to know steps in detail.

Till Now, we've created an android application with name ViewPager. So, We'll follow below steps to use viewPager.

  • Modify values folder.
  • Create Fragment pages to be used in the ViewPager.
  • Create PagerAdapter For ViewPager.
  • Defined PagerTabStrip to show title with page.
  • Define ViewPager in xml file.
  • Access ViewPager in java file and Perform Some operations.

Open res/values/strings.xml file. Then, add below code into it.

<resources>
<string name="app_name">ViewPager</string>
<string name="no_image">No Image</string>
<string name="tutorial_by">Tutorial By UKAcademe.com</string>
<string name="first_fragment">First Fragment</string>
<string name="second_fragment">Second Fragment</string>
<string name="third_fragment">Third Fragment</string>
</resources> 

Don’t worry, these string constants will be used later in this tutorial later.

In this application, we will add three pages in ViewPager. So, we need to create three fragments and it’s xml file. Below is the name of the three fragment that we are going to create now.

  • FirstFragment.java and first_fragment.xml file
  • SecondFragment.java and second_fragment.xml file
  • ThirdFragment.java and third_fragment.xml file

Let’s create the view now.

Create a new xml file in res/layout folder and name it first_fragment.xml. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="@android:color/holo_orange_dark">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="@string/first_fragment"
android:textColor="@android:color/white"
android:textSize="18sp"
android:textStyle="bold"/>

<ImageView
android:id="@+id/Image"
android:src="@drawable/ukacademe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:contentDescription="@string/no_image"/>

<TextView
android:id="@+id/TextView"
android:text="@string/ukacademe_tutorial"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="17sp"/>

</LinearLayout> 

Then, create a new java file in src/main/java/com.ukacademe.viewpager folder and name it FirstFragment.java. Then, add below code into it.

package com.ukacademe.viewpager;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FirstFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.first_fragment, container, false);
        return view;
    }

}

 

 

 

 

create a new xml file in res/layout folder with name second_fragment.xml. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center" android:background="@android:color/holo_red_light">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="@string/second_fragment"
android:textColor="@android:color/white"
android:textSize="18sp"
android:textStyle="bold"/>

<ImageView
android:id="@+id/Image"
android:src="@drawable/ukacademe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:contentDescription="@string/no_image"/>

<TextView
android:id="@+id/TextView"
android:textStyle="bold"
android:text="@string/ukacademe_tutorial"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="17sp"/>

</LinearLayout>

Then, Create a new java file in src/main/java/com.ukacademe.viewpager folder and name it SecondFragment.java. Then, add below code into it.

com.ukacademe.viewpager;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class SecondFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.second_fragment, container, false);
        return view;
    }

}

Create a new xml file in res/layout folder with name third_fragment.xml. Then, add below code into it.

 

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@android:color/holo_orange_light"
android:gravity="center">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="@string/third_fragment"
android:textColor="@android:color/white"
android:textSize="18sp"
android:textStyle="bold"/>

<ImageView
android:id="@+id/Image"
android:src="@drawable/ukacademe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:contentDescription="@string/no_image"/>

<TextView
android:id="@+id/TextView"
android:text="@string/ukacademe_tutorial"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="17sp"/>

</LinearLayout>

Then, create a new java file in src/main/java/com.ukacademe.viewpager folder and name it ThirdFragment.java. Then, add below code into it.

package com.ukacademe.viewpager;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class ThirdFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.third_fragment, container, false);
        return view;
    }

}

Till Now, we have created three views that will be used by PagerAdapter to create pages for viewPager. Let’s create pagerAdapter now.

As we already know, adapter is used to provide views. Here, we will use PageAdapter to provide views for ViewPager. Basically, it creates views for each page in the ViewPager. So, let’s create a new file with name ViewPagerAdapter.java in main/java/com.ukacademe.viewpager folder. Then, add below code into it.

package com.ukacademe.viewpager;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class ViewPagerAdapter extends FragmentPagerAdapter {

    private int COUNT = 3;

    ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new FirstFragment();
                break;
            case 1:
                fragment = new SecondFragment();
                break;
            case 2:
                fragment = new ThirdFragment();
                break;
        }

        return fragment;
    }

    @Override
    public int getCount() {
        return COUNT;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return "Tab " + (position + 1);
    }

}

We have extended ViewPagerAdapter class with FragmentPagerAdapter class. Some of the advantages of using FragmentPagerAdapter are as below –

 

 

 

 

  • It is a subclass of PagerAdapter that represents each page as fragment that is persistently kept in the fragment manager as long as the user can return to the page.
  • This is best for use with static fragments to be paged through such as set of tabs. The fragments that user visits will be kept in memory, through view hierarchy will be destroyed when not visible. This can result use of significant amount of memory. So, Use it when data does not change constantly or frequently.
  • When using FragmentPagerAdapter the host ViewPager must have a valid ID set.
  • Subclass only need to implement getItem(int) and getCount() method to have working adapter.

Note :– If you want to implement views that changes frequently, you can create a subclass of FragmentStatePagerAdapter instead of FragmentPagerAdapter.

Now, we will define PagerTabStrip to show title with each page. We add PagerTabStrip with ViewPager in xml file to show title of each page. It helps to identify previous, current and next page in ViewPager. It gets title from ViewPagerAdapter class. Note that we have defined getPageTitle(int position) method in ViewPagerAdapter class that are responsible for title of each page. Below is code snippet of PagerTabStrip.

<android.support.v4.view.PagerTabStrip
android:id="@+id/pager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="@color/colorPrimary"
android:padding="10dp"/>

Open res/layout/activity_main.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">

<android.support.v4.view.ViewPager
android:id="@+id/ViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.view.PagerTabStrip
android:id="@+id/pager_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="@color/colorPrimary"
android:padding="13dp" />

</android.support.v4.view.ViewPager>

</android.support.constraint.ConstraintLayout>

In activity_main.xml file, we have defined ViewPager. Note that we have also defined PagerTabStrip that are responsible to show title of each page. Now, we will access this ViewPager and PagerTabStrip and perform some operations on it.

Open src/main/java/com.ukacademe.viewpager/MainActivity.java file. Then, add below code into it.

package com.ukacademe.viewpager;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = findViewById(R.id.ViewPager);
        if (viewPager != null) {
            ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
            viewPager.setAdapter(adapter);
        }

    }
}

 

 

 

 

In java file, we have accessed Android ViewPager. Then, we have created a class of ViewPagerAdapter class and set this adapter to ViewPager. This adapter will be responsible to create views in ViewPager.

Since the file of AndroidManifest.xml is very important in any android application, we are also going to see the content inside this file.

Code inside src/main/AndroidManifest.xml file is as below –

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ukacademe.viewpager">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

When we run the program, we will get output as shown below.

UK Academe-ViewPager-Output