Search code examples
javaandroidandroid-viewpager

How to make an Android ViewPager that is continuous?


All of the ViewPager examples that I've found online seem to have a static number of pages that you can swipe through. My app is for my music blog, and I want the user to be able to click a post which opens my SinglePostActivity. It should show the post, then allow the user to swipe the views to be able to see the previous post and next post.

Obviously, I don't want to have to load all of the posts and add them to a ViewPager, but load the post that the user clicked, and the previous and next posts so the user will see them as they're swiping. Once a swipe to the next post is complete, it would have to load the post after that so the user can swipe to that one (and vice versa if they swipe to view the previous post).

Are there any Android examples of how to achieve something like this?


Solution

  • You have to create your own PostStatePagerAdapter class by extending FragmentStatePagerAdapter:

    public PostStatePagerAdapter extends FragmentStatePagerAdapter {
        private List data = null;
    
        public PostStatePagerAdapter(FragmentManager fm, List data){
            super(fm);
            this.data = data;
    
        }
    
    @Override
    public Fragment getItem(int arg0) {
            fragmentdata = data.get(arg0)
    
           // create your new fragment that displays your music blog entry by using fragment data got from data list
           return <your fragment>;
        }
    
    
        @Override
    public int getCount() {
        return data.size();
    }
    }
    

    and in your activity class' onCreate()

            PostStatePagerAdapter adapter = new                PostStatePagerAdapter(getSupportFragmentManager(), dataList);
    
            ViewPager viewPager = (ViewPager) findViewById(R.id.postPager); // defined in layout xml
            viewPager.setAdapter(adapter);
               // pass your clicked item index to this activity and set it as view pager's current item
            viewPager.setCurrentItem(index);
    

    Remember to extend this activity class from FragmentActivity

    Hope this helps.