Augment Android's ViewPager with wrap-around functionality.

Overview

Infinite View Pager

Augment Android's ViewPager with wrap-around functionality. Original StackOverflow question: http://stackoverflow.com/questions/7546224/viewpager-as-a-circular-queue-wrapping

Problem

With a normal ViewPager, you can only scroll from the first page to second page (and so forth), from left-to-right. Once you reach the last page, your only option is to scroll backwards, right-to-left. In other words, 'wrap-around scrolling' (going from first-to-last, and last-to-first) is not possible.

Solution

Use the InfiniteViewPager in your Activity/Fragment layout:

<com.antonyt.infiniteviewpager.InfiniteViewPager
	android:id="@+id/pager"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent" />

Wrap your existing PagerAdapter with the InfinitePagerAdapter:

PagerAdapter wrappedAdapter = new InfinitePagerAdapter(adapter);
viewPager.setAdapter(wrappedAdapter);

Gradle build

To install the demo application to your device run the following task:

$ ./gradlew installDebug

To deploy the library to your local Maven repository run the following task:

$ ./gradlew install

Then, to use the library in your project add the following to your build.gradle:

dependencies {
    compile 'com.antonyt.infiniteviewpager:library:1.0.0'
}

Wrapped scrolling should now be possible with your ViewPager. The pages you see are not duplicates - each page from your PagerAdapter is only created once and then reused. This means you do not have to worry about managing multiple instances of the same Fragment.

Caveats

It is only possible to achieve wrapping when you have at least 4 pages. This is because of the way the ViewPager creates, destroys, and displays the pages. No fix for the general case has been found.

Comments
  • ViewPager sometimes displays 'empty' pages

    ViewPager sometimes displays 'empty' pages

    I've noticed that when you initialize a fragment with this ViewPager, navigate away then navigate 'Back'; an empty page is shown. After navigating back to this fragment, you can continue to swipe on the pager, then after X amount of items the view pager it against populated with more items.

    Initializing a fragment with this ViewPager seems to work fine; however, coming back to a fragment that had already been created creates some blank pages.

    opened by aeroechelon 10
  • Class Not Found Exception

    Class Not Found Exception

    Hello, I am facing the problem of class not found exception in my project when i used your code. And I am using your code with actionbar sherlock You are passing color array and I am passing image array. and I have already added your InfiniteViewPager.java and InfinitePagerAdapter as it is . Here is ,my code and log cat.

    Log Cat :-

    12-26 10:24:58.648 1157-1157/com.bito1.Shoplu E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bito1.Shoplu/com.bito1.Shoplu.Main.actMain}: android.view.InflateException: Binary XML file line #8: Error inflating class com.antonyt.infiniteviewpager.InfiniteViewPager at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) at android.app.ActivityThread.access$600(ActivityThread.java:141) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5103) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class com.antonyt.infiniteviewpager.InfiniteViewPager at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:707) at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) at android.view.LayoutInflater.inflate(LayoutInflater.java:492) at android.view.LayoutInflater.inflate(LayoutInflater.java:397) at android.view.LayoutInflater.inflate(LayoutInflater.java:353) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267) at com.actionbarsherlock.internal.ActionBarSherlockNative.setContentView(ActionBarSherlockNative.java:133) at com.actionbarsherlock.app.SherlockFragmentActivity.setContentView(SherlockFragmentActivity.java:261) at com.bito1.Shoplu.Main.actMain.onCreate(actMain.java:26) at android.app.Activity.performCreate(Activity.java:5133) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)             at android.app.ActivityThread.access$600(ActivityThread.java:141)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)             at android.os.Handler.dispatchMessage(Handler.java:99)             at android.os.Looper.loop(Looper.java:137)             at android.app.ActivityThread.main(ActivityThread.java:5103)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:525)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)             at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.ClassNotFoundException: Didn't find class "com.antonyt.infiniteviewpager.InfiniteViewPager" on path: DexPathList[[zip file "/data/app/com.bito1.Shoplu-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.bito1.Shoplu-1, /vendor/lib, /system/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:53) at java.lang.ClassLoader.loadClass(ClassLoader.java:501) at java.lang.ClassLoader.loadClass(ClassLoader.java:461) at android.view.LayoutInflater.createView(LayoutInflater.java:559) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)             at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)             at android.view.LayoutInflater.inflate(LayoutInflater.java:492)             at android.view.LayoutInflater.inflate(LayoutInflater.java:397)             at android.view.LayoutInflater.inflate(LayoutInflater.java:353)             at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267)             at com.actionbarsherlock.internal.ActionBarSherlockNative.setContentView(ActionBarSherlockNative.java:133)             at com.actionbarsherlock.app.SherlockFragmentActivity.setContentView(SherlockFragmentActivity.java:261)             at com.bito1.Shoplu.Main.actMain.onCreate(actMain.java:26)             at android.app.Activity.performCreate(Activity.java:5133)             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)             at android.app.ActivityThread.access$600(ActivityThread.java:141)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)             at android.os.Handler.dispatchMessage(Handler.java:99)             at android.os.Looper.loop(Looper.java:137)             at android.app.ActivityThread.main(ActivityThread.java:5103)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:525)

    I am attching my Main Activity and main.xml and my fragment class file. so please check out and let me know the solution.

    MainActivity:-

    public class actMain extends SherlockFragmentActivity implements View.OnClickListener {

    Button BTN_FACEBOOK;
    ViewPager PAGER;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        initiatePageControls();
    
        startTour();
    }
    
    private void startTour() {
        PagerAdapter _adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            int[] _images = new int[]{R.drawable.ic_launcher, R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d};
    
            @Override
            public int getCount() {
                return _images.length;
            }
    
            @Override
            public Fragment getItem(int position) {
                Fragment _fragment = new frg_tour_slide();
    
                Bundle _args = new Bundle();
                _args.putInt("images", _images[position]);
                _args.putInt("position", position);
                _fragment.setArguments(_args);
    
                return _fragment;
            }
        };
    
        PagerAdapter _wrappedAdapter = new InfinitePagerAdapter(_adapter);
        PAGER.setAdapter(_wrappedAdapter);
    }
    
    private void initiatePageControls() {
        BTN_FACEBOOK = (Button) findViewById(R.id.btnFacebook);
        BTN_FACEBOOK.setOnClickListener(this);
        PAGER = (ViewPager) findViewById(R.id.pager);
    }
    
    @Override
    public void onClick(View view) {
        if (view.getId() == BTN_FACEBOOK.getId()) {
            startActivity(new Intent(getApplicationContext(), actTestService.class));
            //startActivity(new Intent(getApplicationContext(), actFacebook.class));
        }
    }
    

    }

    Fragment :- public class frg_tour_slide extends SherlockFragment {

    ImageView SLIDE_1;
    private int IMAGES;
    private int IMAGE_POSITION;
    private Context CONTEXT;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        IMAGES = args.getInt("images");
        IMAGE_POSITION = args.getInt("position");
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
        View _view = inflater.inflate(R.layout.tour_slide, null);
    
        SLIDE_1 = (ImageView) _view.findViewById(R.id.imgSlideShow);
        SLIDE_1.setImageResource(IMAGES);
    
        return _view;
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("dummy", true);
    }
    

    }

    Please help me for this issue. Thanking you in advance.

    opened by riddhishah1989 7
  • How to make Scrolling fast?

    How to make Scrolling fast?

    Hello, i used your this custom infinite view pager for rotate globe with custom images but currently its scrolling speed is slow so how to increase its scrolling speed or make it smooth scroll. I want to give scrolling speed dynamically. Please give me any solution or positive response. Thanks

    opened by solankiranvir 2
  • Open source license

    Open source license

    Love your code... it's exactly what I've been looking for. I can't use it in my app though unless I know the terms of the license. Would you mind adding a license to your repository? Thanks so much!!!!

    Ingrid

    opened by itruemper 2
  • onCreateOptionsMenu not called in child fragment when using FragmentPagerAdapter

    onCreateOptionsMenu not called in child fragment when using FragmentPagerAdapter

    That's because setPrimaryItem() is not forwarded to set adapter instance. To make it work, add the method below to InfinitePagerAdapter class:

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        adapter.setPrimaryItem(container, position, object);
    }
    

    Inside setPrimaryItem() FragmentPagerAdapter calls setMenuVisibility() on fragments to ensure only one would get menu callbacks. Without calling setPrimaryItem() all fragments have menu visibility set to false by default.

    opened by Enmankan 1
  • setUserVisibleHint(boolean isVisible) not being called for Fragments when they surface!

    setUserVisibleHint(boolean isVisible) not being called for Fragments when they surface!

    I have many user delight items in my app that need to surface when, or shortly after, a user swipes to a tab and that tab is made visible. I was using a regular viewpager before and this was no issue. Can't seem to find where/how I might get the InfiniteViewPager to do this. May need to hack the support-v4 library and recompile jar.

    opened by kfieldi5 1
  • Update a bunch of dependencies

    Update a bunch of dependencies

    This updates:

    1. Gradle wrapper
    2. Android Gradle plugin (this required removing buildToolsVersion)
    3. Android Maven plugin (I'm not sure how to test this, but the old version didn't work with the rest of the changes)
    4. Support library (this required bumping up minSdkVersion and compileSdkVersion) - I also started using the specific packages that are required, rather than the whole kitchen-sink support library, to reduce the size
    opened by scottkennedy 0
  • Overridden two additional methods from ViewPager.

    Overridden two additional methods from ViewPager.

    Since setCurrentItem() refers to a "real" position and not "virtual" position, override the implementation of getCurrentItem() to reflect this. It now returns the actual position of the object that is backing the adapter.

    Also fixes #8 setCurrentItem(int, boolean) has the same implementation as setCurrentItem(int) except with smoothScroll

    opened by aeroechelon 0
  • Updated getCurrentItem() to reflect the object position in adapter.

    Updated getCurrentItem() to reflect the object position in adapter.

    Overridden getCurrentItem() to reflect the actual object position that corresponds to the position in the data backing the adapter. Similar to setCurrentItem().

    opened by aeroechelon 0
  • get Current Item from InfiniteViewPager

    get Current Item from InfiniteViewPager

    Hello,

     I would like to get the current Item from InfiniteViewPager. I have tried to get the current item. But I haven't got the current Item. Is there any way to get the current item?
    

    Thanks. julia.

    opened by kyawswa 0
  • Get actual current position of the page

    Get actual current position of the page

    Is there any metghod to get actual current position method, pager.getCurrentRealPosition() is not providing me actual position, and i have call setCurrentRealPosition at last of currentItem method.

    override fun setCurrentItem(item: Int, smoothScroll: Boolean) { var item = item if (adapter!!.count == 0) { super.setCurrentItem(item, smoothScroll) return } item = offsetAmount + item % adapter!!.count super.setCurrentItem(item, smoothScroll) setRealCurrentItem(item, true) }

    opened by vinayappypiellp 1
  • how can i Tablayout with it

    how can i Tablayout with it

    Hi, i want to user tablayout with infiniteviewpager. Can someone guide me.

    Right now i am facing an issue while using it,

    Process: com.kotlin.mNative, PID: 7342 java.lang.OutOfMemoryError: Failed to allocate a 108832 byte allocation with 102312 free bytes and 99KB until OOM, max allowed footprint 268435456, growth limit 268435456 at android.view.ViewGroup.addInArray(ViewGroup.java:5361) at android.view.ViewGroup.addViewInner(ViewGroup.java:5274) at android.view.ViewGroup.addView(ViewGroup.java:5083) at com.google.android.material.tabs.TabLayout.addTabView(TabLayout.java:1370) at com.google.android.material.tabs.TabLayout.addTab(TabLayout.java:620) at com.google.android.material.tabs.TabLayout.addTab(TabLayout.java:605) at com.google.android.material.tabs.TabLayout.populateFromPagerAdapter(TabLayout.java:1323) at com.google.android.material.tabs.TabLayout.setPagerAdapter(TabLayout.java:1314) at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1227) at com.google.android.material.tabs.TabLayout.setupWithViewPager(TabLayout.java:1188)

    opened by vinayappypiellp 0
  • Auto scroll

    Auto scroll

    Hey bro auto scroll crash while using this library this is my logcat

    java.lang.NullPointerException: Attempt to invoke virtual method 'int android.support.v4.view.PagerAdapter.getCount()' on a null object reference

    opened by MustafaAndroid 0
  • Sometimes there will be blank pages (the data has been set to more than 4)?

    Sometimes there will be blank pages (the data has been set to more than 4)?

    In my case, I play loop it in the timertask and change viewpagerTransform every time (It's like random animation),But there will always be a blank page at some time.

    private Handler mh = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                moveNextPosition();
           }
    };
    

    Any help is greatly appreciated

    opened by dtboy1995 0
Owner
Antony Tran
Antony Tran
UltraViewPager is an extension for ViewPager to provide multiple features in a single ViewPager.

UltraViewPager 中文文档 ProjectUltraViewPager is a ViewPager extension that encapsulates multiple features, mainly to provide a unified solution for multi

Alibaba 5k Dec 20, 2022
Pixplicity 915 Nov 8, 2022
Don't write a ViewPager Adapter! Hook up your ViewPager to your data model using Android Data Binding Framework. With Kotlin support!

Don't write a ViewPager Adapter! Hook up your ViewPager to your data model using Android Data Binding Framework. Show some ❤️ ?? Sweet and short libra

Rakshak R.Hegde 180 Nov 18, 2022
Persons cards list viewpager - Persons cards list viewpager using kotlin

persons_cards_list_viewpager Дизайн и условие взяты из https://github.com/appKOD

Mironov Ury 1 Mar 1, 2022
Library containing common animations needed for transforming ViewPager scrolling for Android v13+.

ViewPagerTransforms Library containing common animations needed for transforming ViewPager scrolling on Android v13+. This library is a rewrite of the

Ian Thomas 2.5k Dec 31, 2022
Paging indicator widgets compatible with the ViewPager from the Android Support Library and ActionBarSherlock.

Android ViewPagerIndicator Paging indicator widgets that are compatible with the ViewPager from the Android Support Library to improve discoverability

Jake Wharton 10.2k Jan 3, 2023
A custom ViewPager title strip which gives continuous feedback to the user when scrolling

SmartTabLayout A custom ViewPager title strip which gives continuous feedback to the user when scrolling. This library has been added some features an

ogaclejapan 7k Jan 1, 2023
A Material Design ViewPager easy to use library

MaterialViewPager Material Design ViewPager easy to use library Sample And have a look on a sample Youtube Video : Youtube Link Download In your modul

Florent CHAMPIGNY 8.2k Dec 29, 2022
A different beautiful ViewPager, with quick swipe controls

HollyViewPager Usage Add a HollyViewPager in your layout <com.github.florent37.hollyviewpager.HollyViewPager android:id="@+id/hollyViewPager"

Florent CHAMPIGNY 1.1k Dec 9, 2022
An interactive indicator to navigate between the different pages of a ViewPager

Android PagerSlidingTabStrip (default Material Design) This library is not maintained anymore and there will be no further releases. For most of the c

JPARDOGO 2.2k Jan 4, 2023
Combine ViewPager and Animations to provide a simple way to create applications' guide pages.

WoWoViewPager WoWoViewPager combines ViewPager and Animations to provide a simple way to create applications' guide pages. When users are dragging WoW

黄伟平 2.7k Dec 30, 2022
An android ViewPager extension allowing infinite scrolling

NO LONGER MAINTAINED LoopingViewPager An android ViewPager extension allowing infinite scrolling. You can use it with "standart" PagerAdapter (inflati

Leszek Mzyk 992 Nov 10, 2022
ViewPager that slides vertically.

ExpandablePager Layout that contains a ViewPager and can slide vertically between 2 states (expanded and collapsed). #Requirements Android 4.0+ (Ice C

Telenav Inc 716 Sep 15, 2022
[Development stopped in 2014. Unfinished and not stable - not recommended to use.] An easy-to-use ViewPager subclass with parallax background effect for Android apps.

Development stopped in 2014 Not developed since 2014. Unfinished and not stable - not recommended to use. ParallaxViewPager An easy-to-use ViewPager s

Andras Kindler 437 Dec 29, 2022
Android - A ViewPager page indicator that displays the current page number and (optionally) the page count

NumericPageIndicator A ViewPager page indicator that displays the current page number and (optionally) the page count. It can also display buttons to

Manuel Peinado Gallego 253 Nov 16, 2022
Pager (especially for ViewPager) indicator in two styles: circle & fraction.

PagerIndicator Pager (especially for ViewPager) indicator in two styles: circle & fraction. Demo circle fraction Dependency implementation 'me.liangfe

Fei Liang 212 Nov 28, 2022
Android ViewPager template with cool animation.

glazy-viewpager ViewPager template with cool animation. Preview Dependencies compile 'com.android.support:palette-v7:25.2.0' Usage Refer the implement

Kannan Anbarasan 251 Nov 29, 2022
ViewPager cards inspired by Duolingo

ViewPagerCards ViewPager cards inspired by Duolingo From my blog post: https://rubensousa.github.io/2016/08/viewpagercards This is just a sample proje

Rúben Sousa 4.1k Dec 22, 2022
Paging indicator widgets compatible with the ViewPager from the Android Support Library and ActionBarSherlock.

Android ViewPagerIndicator Paging indicator widgets that are compatible with the ViewPager from the Android Support Library to improve discoverability

Jake Wharton 10.2k Jan 5, 2023