Android Sliding Views Using ViewPager With PagerAdapter,FragmentPagerAdapter

In this tutorial we are going to learn about how to create swipe views in android application. We can create swipe view in android application using the ViewPager widget which is available in the support library. ViewPager is a layout widget which is capable of holding many child views and each child view represent a separate page. To insert child views that represent each page we need to hook up the viewpager to a pagerAdapter. You have two options for the viewpager adapter :

FragmentPagerAdapter : This is the best option if there is only a limited number of pages(Fragment) to show.

FragmentStatePagerAdapter : You can use this adapter if there is large number of pages or the number of pages are indeterminate.

 

 

Here In this tutorial by creating a simple example I will demonstrate you how to swipe between the pages using PagerAdapter and how to swipe between the fragments using FragmentPagerAdapter .

Create new project

1. Create a new project in Android Studio from File ⇒ New Project by filling the required details. When it prompts you to select the activity, choose Empty Activity and continue.

2. Open build.gradle located in app level and add dependency ‘com.android.support:design:27.1.1’ . It is needed for tabLayout widget .

dependencies {
   
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:support-v4:27.1.1'
    //Add this    
    compile 'com.android.support:design:27.1.1'
   
}

3. Create package fragment contains two fragment Yogasan.java and SuryaNamaskar.java .

4. Both fragment will contain pages which we will swipe using viewpager with pagerAdapter.

Using PagerAdapter

PagerAdapter allow us to populate pages inside of a viewpager.

When you implement a PagerAdapter, you must override the following methods at minimum:

  • getCount() – Return the number of views available., i.e., number of pages to be displayed/created in the ViewPager.
  • instantiateItem() – This method will create the page for the given position passed to it as an argument. In our case, we inflate our layout resource which contains one imageView for image and one textView which will contain image related description. Finally, the inflated view is added to the container ( ViewPager) and return it as well.
  • destroyItem() – Removes the page from the container for the given position. We simply removed object using removeView() but could’ve also used removeViewAt() by passing it the position.
  • isViewFromObject() – ViewPager associates each page with a key Object instead of working with Views directly. This key is used to track and uniquely identify a given page independent of its position in the adapter. This method checks whether the View passed to it (representing the page) is associated with that key object(returned by instantiateItem(ViewGroup, int)) or not. It is required by a PagerAdapter to function properly. It returns true if view is associated with the key object .

As we swipe the page the pageAdapter firstly destroys the page previous to the one from which it is coming from by calling destroyItem() and creates the page next to it by calling instantiateItem() .

For example: we have four pages(page1,page2,page3,page4).Suppose currently i am on page2 now as i swipe page2 to move to page3 ,destroyItem() get called  first and destroy the page1(View) and then instantiateItem() get called and a page next to page3 i.e page4 get created.This is how pageAdapter works.

5. Here’s how res/layout/surya_namaskar_content.xml will look like which is inflated in the instantiateItem() method:

surya_namaskar_content.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="190dp"
                android:layout_height="190dp"
                android:layout_alignParentTop="true"
                android:layout_centerInParent="true" />

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imageView"
                android:paddingLeft="8dp"
                android:paddingRight="5dp"
                android:textSize="12dp"
                android:layout_marginTop="10dp"
                android:textStyle="bold" />
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>

6. Open Yogasan.java and SuryaNamaskar.java and write the below code:

Yogasan.java

package com.c1ctech.androidviewpagerexample.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.c1ctech.androidviewpagerexample.R;


public class Yogasan extends Fragment {


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

            View view= inflater.inflate(R.layout.fragment_yogasan, container, false);
            ((ViewPager) view.findViewById(R.id.view_pager_yogashan)).setAdapter(new ImagePagerAdapter());
            return view;
    }


    private class ImagePagerAdapter extends PagerAdapter {
        private int[] mImages;
        private String[] poseDesc;

        private ImagePagerAdapter() {
            this.mImages = new int[]{R.drawable.bitilasan, R.drawable.ardhahalsan, R.drawable.majariasan, R.drawable.sarvangasan, R.drawable.trikonasan, R.drawable.yogic_jugging};
            this.poseDesc = new String[]{"1.Begin in a tabletop position, on your hands and your knees, with your knees stacked directly below your hips and your wrists, elbows and shoulder in line and perpendicular to the floor\n\n2.Center your head in a neutral position as you gaze as the floor\n\n3.As you inhale, lift your sitting bones and sternum toward the ceiling, as your belly sinks toward the floor\n\n4.Lift your head and gaze up", "1.Lie down on your back and breath in. Pull your legs at 90 degrees and slowly try to take your legs towards your head.\n\n2.Ensure that you focus on your breathing and don\u2019t lose control.\n\n3.Only extend your body as easily as possible. Don\u2019t over exert and slowly let your body become more flexible.", "1. Stand on all fours, such that your back forms a table top and your feet and hands from its legs.\n\n2. Your arms should be perpendicular to the floor, and your hands should be placed flat on the floor, right under your shoulders. Your knees should be placed hip-width apart.\n\n3. Look straight ahead.\n\n4. Inhale and raise your chin as you tilt your head backwards. Push your navel down and raise your tailbone. Compress your buttocks. You might feel a tingling sensation.\n\n5. Hold the pose for a few breaths. Breathe long and deep.", "1.Lie on your back with hands by your side.\n\n2.With one movement, lift your legs, buttocks and back so that you come up high on your shoulders. Support your back with the hands.\n\n3.Move your elbows closer towards each other, and move your hands along your back, creeping up towards the shoulder blades. Keep straightening the legs and spine by pressing the elbows down to the floor and hands into the back. Your weight should be supported on your shoulders and upper arms and not on your head and neck.\n\n4.Keep the legs firm. Lift your heels higher as though you are putting a footprint on the ceiling. Bring the big toes straight over the nose. Now point the toes up. Pay attention to your neck. Do not press the neck into the floor. Instead keep the neck strong with a feeling of tightening the neck muscles slightly. Press your sternum toward the chin. If you feel any strain in the neck, come out of the posture.\n\n5.Keep breathing deeply and stay in the posture for 30-60 seconds.\n\n6.To come out of the posture, lower the knees to forehead. Bring your hands to the floor, palms facing down. Without lifting the head slowly bring your spine down, vertebra by vertebra, completely to the floor. Lower the legs to the floor. Relax for a minimum of 60 seconds.", "1.Stand with your feet wide apart as much as possible and at a comfortable distance without losing your balance and poise.\n\n2.Stretch your arms at your sides and breath in. As you breathe in, bring your right hand next to the outside of the left foot and keep the other arm outstretched.\n\n3.Hold in this position for as long as possible. Do not bend your knees or arms. Try to stretch as much as possible. ", "1.You have to stand on both your feet.\n\n2.Stretch the arm at shoulder level and the second arm elbow bent at 90 degrees next to your body.\n\n3.Now, breathe in, extend the folded arms and retract the arm that you had extended. At the same time, move your leg opposite to the extended arm and ensure you lift it up as much as possible.\n\n4.This full extension of the arms and legs leaves you breathless and burns a lot of calories, expands your lung capacity and helps streamline the blood purification in the body."};
        }

        public int getCount() {

            return this.mImages.length;
        }

        public boolean isViewFromObject(View view, Object object) {
            return view == ((View) object);
        }

        public Object instantiateItem(ViewGroup container, int position) {
            FragmentActivity activity = getActivity();

            View view = ((LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.surya_namaskar_content, container, false);
            ((TextView) view.findViewById(R.id.textView)).setText(this.poseDesc[position]);
            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setImageResource(this.mImages[position]);
            ((ViewPager) container).addView(view, 0);
            return view;

        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }
    }
}

SuryaNamaskar.java

package com.c1ctech.androidviewpagerexample.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.c1ctech.androidviewpagerexample.R;


public class SuryaNamaskar extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.fragment_surya_namaskar, container, false);
        ((ViewPager) view.findViewById(R.id.view_pager_suryanamaskar)).setAdapter(new ImagePagerAdapter());
        return view;
    }

    private class ImagePagerAdapter extends PagerAdapter {
        private int[] mImages;
        private String[] poseDesc;

        private ImagePagerAdapter() {
            this.mImages = new int[]{R.drawable.posepre, R.drawable.pose1, R.drawable.pose2, R.drawable.pose3, R.drawable.pose4, R.drawable.pose5, R.drawable.pose6, R.drawable.pose7, R.drawable.pose8, R.drawable.pose9, R.drawable.pose10};
            this.poseDesc = new String[]{"Inhale: As you breathe in, lift both arms up from the sides.\nExhale: As you exhale, bring your palms together in front of the chest in prayer position.", "Inhale : Breathing in, lift the arms up.", "Exhale : Exhale completely, bringing your hands down to the floor.", "Inhale : Bring the right foot forward in between the two hands, left knee down to the floor and look up.", "Inhale: As you breathe in, take the right leg back and bring the whole body in a straight line", "Exhale: Gently bring your two hands, two feet, two knees, chest and chin to touch the floor.", "Inhale: Keep your elbows bent and look up.", "Exhale: The inverted V.", "Inhale: Bring the left foot forward in between the two hands, right knee down to the floor and look up.", "Exhale: Bring your right foot forward and try to keep your palms on the floor.", "Inhale: Breathing in, lift the arms up."};
        }

        public int getCount() {
            return this.mImages.length;
        }

        public boolean isViewFromObject(View view, Object object) {
            return view == ((View) object);
        }

        public Object instantiateItem(ViewGroup container, int position) {
            FragmentActivity activity = getActivity();
            View view = ((LayoutInflater) activity.getSystemService("layout_inflater")).inflate(R.layout.surya_namaskar_content, container, false);
            ((TextView) view.findViewById(R.id.textView)).setText(this.poseDesc[position]);
            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setImageResource(this.mImages[position]);
            ((ViewPager) container).addView(view, 0);
            return view;
        }

        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }
    }
}

Using FragmentPagerAdapter

This adapter is used when you want to swipe between the fragments and there is only a limited number of pages(Fragment) to show.

Two main methods that we must override:

getItem(int position) : returns a fragment of specific position.
getCount() : counts the no. of fragments available.

7. Open SharirikActivity.java as I have refracted MainActivity.java as SharirikActivity.java and write the below code:

SharirikActivity.java

package com.c1ctech.androidviewpagerexample;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import com.c1ctech.androidviewpagerexample.fragment.SuryaNamaskar;
import com.c1ctech.androidviewpagerexample.fragment.Yogasan;

import java.util.ArrayList;
import java.util.List;

public class SharirikActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar();

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new Yogasan(), "YOGASHAN");
        adapter.addFragment(new SuryaNamaskar(), "SURYANAMASKAR");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

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

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

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

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

When you run the app it will look like this as shown below:

That’s all for this tutorial .I hope it is helpful for you to understand the working of viewpager with pagerAdapter,FragmentPagerAdapter.

Leave a Reply