ZOFTINO.COM

Android ViewPager with Custom Pager Adapter

You can create swipe view feature in your android app to allow users of your app to flip right or left to view through pages of your app. Android framework provides ViewPager class to implement swipe view or flip view functionality. ViewPager class works with pager adapter which provides pages.

To implement swipe view functionality in your app, you need to define ViewPager in the activity layout xml fileyou’re your activity, after setting content view, you need to get the view pager object defined in layout xml and set pager adapter for the view pager.

Android framework provides FragmentPagerAdapter and FragmentStatePagerAdapter pager adapters. Both of them represent each page as Fragments. If you have few pages to show in view pager, FragmentPagerAdapter is the best choice as it keeps fragments in fragment manger and servers pages directly from fragment manger if one exists. FragmentStatePagerAdapter works best in many-pages scenarios.

Representing each page as fragment works for most of the scenarios. But if you want to create your own pager adapter for your requirement, it is easy to do so. You need to implement PagerAdapter, see below example to know how to create custom pager adapter.

Add PagerTitleStrip to ViewPager in layout xml file to display title for each page. PagerTitleStrip helps indentify previous, current and next pages of a view pager. PagerTitleStrip displays next, current and previous page titles of view pager at top or bottom of the screen. PagerTitleStrip gets page title from view pager adapter. View pager adapter getPageTitle method provides page titles of view pager.

Below are Viewpager examples. First one shows how to implement view pager with FragmentPagerAdapter and second example shows how to create and use custom pager adapter.

android viewpager with custom pager adapter example

ViewPager with FragmentPagerAdapter

I am going to show how to use ViewPager with coupons app example. In this example, coupons data for a particular store is treated as a page.

First we need to create a Fragment which is served as page by ViewPager. The example fragment has a factory method which takes store name parameter, creates new fragment instance and sets store name as fragment argument. Fragment’s onCreate call back method returns list view containing coupons for the store.

Now, a sub class of FragmentPagerAdapter needs to be created to provide implementation of getItem, getCount and getPageTitle of PagerAdapter. In getItem method, fragment instance is created using the page index and returned. You need to define ViewPager and PagerTitleStrip in layout xml file.

Activity

 package com.zoftino.viewpager;

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

public class FragmentsSliderActivity extends AppCompatActivity {

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

        FragmentsViewPagerAdapter storePagerAdpter =  new FragmentsViewPagerAdapter(getSupportFragmentManager());
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewPagerFragments);
        viewPager.setAdapter(storePagerAdpter);
    }
}
 

Activity layout xml

 

    
        
    

 

Fragment

 package com.zoftino.viewpager;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class StoreCouponsFragment extends Fragment{

    public static StoreCouponsFragment newInstance(String storeName) {
        StoreCouponsFragment storeCouponsFragment = new StoreCouponsFragment();

        Bundle args = new Bundle();
        args.putString("storeName", storeName);
        storeCouponsFragment.setArguments(args);

        return storeCouponsFragment;
    }

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

        ArrayList<String> coupons = new ArrayList<String>();
        if(getArguments() != null){
            String storeName = getArguments().getString("storeName");
            coupons = StoreCouponData.storeCoupons.get(storeName);
        }

        ListView listView = new ListView(getActivity());
        listView.setAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, coupons));

        return listView;
    }
}
 

Pager adapter

 package com.zoftino.viewpager;

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

public class FragmentsViewPagerAdapter extends FragmentPagerAdapter {


    public FragmentsViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        String currentStore = (String) (StoreCouponData.storeCoupons.keySet().toArray())[i];
        Fragment fragment = StoreCouponsFragment.newInstance(currentStore);
        return fragment;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return (String) (StoreCouponData.storeCoupons.keySet().toArray())[position];
    }

}
 

ViewPager with custom pager adapter

Custom pager adapter can be created by extending PagerAdapter class. PagerAdapter class has several call back methods which view pager calls. Most important methods which need to be implemented are instantiateItem, destroyItem, getCount and getPageTitle. This example custom pager adapter represents each page as ListView. ListView with appropriate content is created and added to container view in instantiateItem method.

Custom pager adapter

package com.zoftino.viewpager;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.Map;

public abstract class ListViewPagerAdapter extends PagerAdapter {

    private Context mContext = null;
    private Map<String, View> viewState = new HashMap<String, View>();

    public ListViewPagerAdapter(Context ctx ){
        mContext = ctx;
    }
    public abstract View getView(int position);

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View v = (View) getView(position);
        container.addView(v);
        return v;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View)object);
    }
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (View)object == view;
    }


    public Context getmContext() {
        return mContext;
    }
}

Full implementation of pager adapter

package com.zoftino.viewpager;


import android.content.Context;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class CouponsPagerAdapter extends ListViewPagerAdapter {

    public CouponsPagerAdapter(Context ctx) {
        super(ctx);
    }

    public View getView(int position) {
        String currentStore = (String) (StoreCouponData.storeCoupons.keySet().toArray())[position];

        ListView listView = new ListView(getmContext());
        listView.setAdapter(new ArrayAdapter<String>(getmContext(),
                android.R.layout.simple_list_item_1, StoreCouponData.storeCoupons.get(currentStore)));
        return listView;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return (String) (StoreCouponData.storeCoupons.keySet().toArray())[position];
    }
}

Activity

package com.zoftino.viewpager;


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

public class CustomSliderActivity extends AppCompatActivity {

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

        CouponsPagerAdapter storePagerAdpter =  new CouponsPagerAdapter(this);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewPagerCustom);
        viewPager.setAdapter(storePagerAdpter);
    }
}

Layout xml