How to create a carousel using viewpager and fragm

2020-06-27 02:26发布

问题:

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.

回答1:

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));
    }
});


回答2:

You can take help from Gamma Developer guide to make a carousel.

Here is the link



回答3:

Hey not sure whether it is a proper solution or not but i just added one line

 pager.setPageMargin(getResources().getDisplayMetrics().widthPixels /-7);

and now my view shows a portion of the left and right fragments also