ViewPager with previous and next page boundaries

I have a similar solution:

On the viewpager set left and right padding, e.g. 20dp. Do also set the page margin on the viewpager, e.g. half of the pager padding. And do not forget to disable clip padding.

tilePager.setPadding(defaultGap, 0, defaultGap, 0);
tilePager.setClipToPadding(false);
tilePager.setPageMargin(halfGap);

Quoting myself from a blog post on this subject:

The third approach comes from Dave Smith, co-author of the well-regarded book Android Recipes. He went in a very different direction, using a custom container that disabled children clipping to show more than one page at a time.

His published sample code shows the whole thing in action. His container (com.example.pagercontainer.PagerContainer) wraps the ViewPager and calls setClipChildren(false); on itself, so even though the ViewPager is focused on one selected page, other pages that have coordinates beyond the ViewPager bounds are still visible, so long as they fit within the PagerContainer. By sizing the ViewPager to be smaller than the PagerContainer, the ViewPager can size its pages to that size, leaving room for other pages to be seen. PagerContainer, though, needs to help out a bit with touch events, as ViewPager will only handle swipe events on its own visible bounds, ignoring any pages visible to the sides.

enter image description here


  1. Set left and right padding for whole item view. Example xml (page_item.xml):

    <?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:paddingLeft="20dp"
    android:paddingRight="20dp"/>
    
    <TextView
        android:id="@+id/text1"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    
    </LinearLayout>
    
  2. Then set negative page margin for PageView equal to 2*(previous view padding)

    int margin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20*2,     getResources().getDisplayMetrics());
    mViewPager.setPageMargin(-margin);
    
  3. Optional. Set zero left padding for first item and zero right padding to last item to hide empty edges. You may do this in the PageAdapter or Page fragment class.


To show preview of left and right pages set the following two values

viewpager.setClipToPadding(false)
viewpager.setPadding(left,0,right,0)

If you need space between two pages in the viewpager then add viewpager.setPageMargin(int)

Android ViewPager - Show preview of page on left and right