Android ViewPager With Fragment Tutorial With Example

Hello Readers! In this post, we are going to learn about how to use android viewPager with fragments in any android application. Here, we will create three screens using android viewPager and pagerAdapter to flip left and right.

Output

Tutorialwing Android ViewPager Output Android ViewPager Tutorial With Example

Tutorialwing Android ViewPager Output

Getting Started

Android ViewPager can be defined as below –

ViewPager is layout manager that allows the user to flip left and right throughs pages of data.

ViewPager is found in support library. We use PagerAdapter to create pages and provide it to the viewPager.




Example of Android ViewPager With Fragments

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

1. Creating New Project

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

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as ViewPager. Then, click next button.
3. Select minimum SDK you need. However, we have selected 17 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 post to create a new project to know steps in detail.

Till Now, we have created an android application with name ViewPager. So, We will follow below steps to use viewPager.
A. Modify values folder.
B. Create Fragment pages to be used in the ViewPager.
C. Create PagerAdapter For ViewPager.
D. Defined PagerTabStrip to show title with page.
E. Define ViewPager in xml file.
F. Access ViewPager in java file and Perform Some operations.

2.1 Modify Values folder

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 Tutorialwing.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.

2.2 Create Fragment Pages to be used in the viewPager

In this application, we will add three pages in viewPager. So, we need to create three fragment and it’s xml file. Below are the three fragments name that we are going to create now.
(1) FirstFragment.java and first_fragment.xml file
(2) SecondFragment.java and second_fragment.xml file
(3) ThirdFragment.java and third_fragment.xml file

Let’s create the view now.

2.2.1 Create First Fragment and it’s xml file

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

package com.tutorialwing.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 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);
		TextView textView = view.findViewById(R.id.txtMain);
		textView.setText(R.string.first_fragment);

		ImageView imageView = view.findViewById(R.id.imgMain);
		imageView.setImageResource(R.mipmap.ic_launcher);

		return view;
	}
}

Then, create a new xml file in res/layout folder with name 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:background="@android:color/holo_blue_light"
	android:gravity="center"
	android:orientation="vertical">

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

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

	<TextView
		android:id="@+id/txtMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textColor="@android:color/white"
		android:textSize="17sp"/>

</LinearLayout>

2.2.2 Create Second Fragment and it’s xml file

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

package com.tutorialwing.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 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);
		TextView textView = view.findViewById(R.id.txtMain);
		textView.setText(R.string.second_fragment);

		ImageView imageView = view.findViewById(R.id.imgMain);
		imageView.setImageResource(R.mipmap.ic_launcher);

		return view;
	}
}

Then, 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:background="@android:color/holo_red_dark"
	android:gravity="center"
	android:orientation="vertical">

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

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

	<TextView
		android:id="@+id/txtMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textColor="@android:color/white"
		android:textSize="17sp"/>

</LinearLayout>

2.2.3 Create Third Fragment and it’s xml file

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

package com.tutorialwing.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);
		TextView textView = view.findViewById(R.id.txtMain);
		textView.setText(R.string.third_fragment);

		ImageView imageView = view.findViewById(R.id.imgMain);
		imageView.setImageResource(R.mipmap.ic_launcher);

		return view;
	}
}

Then, 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:background="@android:color/holo_orange_dark"
	android:gravity="center"
	android:orientation="vertical">

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

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

	<TextView
		android:id="@+id/txtMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textColor="@android:color/white"
		android:textSize="17sp"/>

</LinearLayout>

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

2.3 Create And Use PagerAdapter For Android ViewPager

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.tutorialwing.viewpager folder. Then, add below code into it.

package com.tutorialwing.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 –
(a) 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.
(b) 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.
(c) When using FragmentPagerAdapter the host ViewPager must have a valid ID set.
(d) 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.

2.4 Define PagerTabStrip to Show title With Each Page

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"/>

3. Use Android ViewPager in xml file

Open res/layout/activity_main.xml file. 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.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>

</LinearLayout>

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

4. Access Android ViewPager in java file

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

package com.tutorialwing.viewpager;

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

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 Widget. 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 AndroidManifest.xml file is very important in any android application, we are also going to see the content inside this file.

AndroidManifest.xml

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

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

	<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 above.

That’s end of tutorial on Android ViewPager.

Leave a Reply