How to create a carousel using viewpager and fragmentStatePager Adapter

bourne picture bourne · Jul 8, 2013 · Viewed 8.5k times · Source

I am new to android and i am trying to create a carousel in android. My class structure are as follows

public class PageViewActivity extends FragmentActivity {

    ViewPager pager;
    ...

    public void onCreate(Bundle savedInstanceState) {
       final ViewPager pager = (ViewPager) findViewById(R.id.pager);
       MyPageAdapter pageAdapter = new MyPageAdapter(getSupportFragmentManager(),getBaseContext());
       pager.setAdapter(pageAdapter);
    }

...

public class MyPageAdapter extends FragmentStatePagerAdapter {

    @Override
    public ImageFragment getItem(int position) {
       ...
       return fragment;
    }

    @Override
    public int getCount() {
       return 10;
    }
}

Now my program is working correctly and I am able to put get 10 fragments which I can access by swiping left or right. But I want to show these 10 fragments as a carousel so that the user has a better idea that there are more fragments left or right of the current position.

Can someone please tell me how can I do it.

I did found this url ViewPager carousel using PageContainer not working with FragmentPagerAdapter but there is not much information for a beginner like me.

Answer

92tonywills picture 92tonywills · Jun 7, 2016

For anyone else who comes across this, I used this code to achieve a pretty nice effect.

pager.setPageMargin((int) (getResources().getDisplayMetrics().widthPixels * -0.33));
pager.setOffscreenPageLimit(5);
pager.setPageTransformer(false, new ViewPager.PageTransformer() {
    @Override public void transformPage(View page, float position) {
        page.setScaleX(0.7f - Math.abs(position * 0.4f));
        page.setScaleY(0.8f - Math.abs(position * 0.6f));
        page.setAlpha(1.0f - Math.abs(position * 0.5f));
    }
});