Skip to main content

How to create View Pager of Fragment in android



Viewpager are used when we required sliding window page with different content on each page and Viewpager is the recommended and easy to use method in the scenario where you want to show multiple types of the fragment on the same screen and user can change the contain of the page by just swiping on the page or by toching on the tab bar.

Here in this example, I am using Android Studio 2.2 it is latest version at the time I am writing this blog.

So we are good to start our view pager demo. Steps to create the project are as given below.

  • Click on File

  • Move your mouse to new

  • Click  on New Project

  • select min version and a relevant name of your project.


In this demo I taken the name of the project is ViewPagerExample, you can choose your suitable name as required.
If you want you can test your app here just to ensure that everything is fine and your project are configured correctly.

ViewPager layout 


We need to add the view pager layout to our main activity layout, open the activity_main.xml file and modify it as given below.
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.debugandroid.viewpagerexample.MainActivity">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

Fragment


You can see that we have added out ViewPager in our main layout files. After that, we are here creating three fragments which we will show on each page. Here we are creating a very simple fragment for better understanding and will copy paste the same fragment with three different names and modify the layout files.

Fragment1.java
 package com.debugandroid.viewpagerexample;  
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}

You can see that we have done nothing in this Fragment we just added it and set a layout file fragement1.xml and our onCreateView method returning that layout file. Similarly, we have to create the Fragment2, paste java and Fragment3.java file by just copy paste the file. After creating the both file you have to change the R.layout.fragment2 adn fragement3 corresponding to the Fragment name of contain you want to show.
You may getting the error in red color because yet we have not created our fragment layout file. So create the our Fragment1.xml,Fragment2.xml and Fragment3.xml files. Here below giving you example of Fragment1.xml similarly you can create the Fragment2xml and Fragement3.xml.

Create Layout Files for Fragment


So for creating the layout file right click on layout under res folder and select the new and then layout resource file and give the name as fragement1 and click on finish.
After that you have do some modification in this layout file for adding a simple text view inside our fragment. For that modify your fragment1.xml file as given below.
 <?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/lime">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="18dp"
android:textColor="@android:color/white"
android:text="Fragment 1"/>
</LinearLayout>

Similarly you have to create two more fragment layout file or you can just copy paste the same file with the name of fragment2.xml and fragement3.xml and change the contain inside text view. You may need to add the color code as well in your color.xml file for setting the background color of our linear layout.

Create ViewPager Adapter


Next we have to create a view pager adapter witch will inflate and show our different-different fragment as you change the page. For example in this demo Fragment1 will be show on position zero, Fragment2 on position 1 and so on.
PageAdapter.java
 package com.debugandroid.viewpagerexample;  
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PageAdapter extends FragmentPagerAdapter {
private FragmentManager fm;
public PageAdapter(FragmentManager fm){
super(fm);
this.fm=fm;
}
@Override
public Fragment getItem(int position) {
Fragment fragment=null;
if(position==0){
fragment=new Fragment1();
}
if(position==1){
fragment=new Fragment2();
}
if(position==2){
fragment=new Fragment3();
}
return fragment;
}
@Override
public int getCount() {
return 3;
}
@Override
public int getItemPosition(Object object)
{
return POSITION_UNCHANGED;
}
}

Here two method are important which we are overriding here inside our view pager adapter one is the getItem() and other one is the getCount(). getItem() method will return our fragment on the basis of page position and getCount() give number of item count in our view pager.

Set ViewPager Adapter


Next we have to combined the all stuff together and test our application. So open the MainActivity.java file and modify it as given below.
 package com.debugandroid.viewpagerexample;  
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private PageAdapter pageAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager= (ViewPager) findViewById(R.id.viewPager);
pageAdapter=new PageAdapter(getSupportFragmentManager());
viewPager.setAdapter(pageAdapter);
}
}

You can see that in above code we are declaring two variable viewPager and pageAdapter and simply initializing it.
viewPage=(ViewPager)findViewById(R.id.viewPager);
using above code we initializing our view pager on the basis of viewpager ID that we have set during our view pager declaration in our main layout file. In next line we are initializing our view pager adapter and passing the FragmentManger as argument and lastly we are setting the adapter using setAdapter method.
We are set to test our application now, you click on run and select the emulator or any other connected device. you will get the output as given below.
View Pager Screenshots



You can download the source code from here.

Comments

  1. […] note I was showing you this example inside the app which we have created in our last post, you can refer it if you have not gone through the last […]

    ReplyDelete

Post a Comment

Popular posts from this blog

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit.
What is Retrofit?
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.

Further, you can check the Retrofit Library here.

So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
Prerequisite for using the Retrofit for WordPress Android App
There is s…

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View.

Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android
Just go to the android folder and open it in separate windows. We will have the following project structure.









Create the Activity Just right click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project sync completed.
Update the project build config …