How to create carousel ViewPager?

前端 未结 3 1456
夕颜
夕颜 2021-02-04 17:13

All I want to do is a horizontal carousel in Android.

If I have 3 screens A B and C then I want my ViewPager to allow me to move like A <-> B, B <-> C, C <->

3条回答
  •  一个人的身影
    2021-02-04 17:37

    ViewPager settings:

        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mViewPager.setAdapter(new YourPagerAdapter(getSupportFragmentManager()));
        //Set the number of pages that should be retained to either side of the current page.
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setCurrentItem(50);
    

    FragmentPagerAdapter:

    public class YourPagerAdapter extends FragmentPagerAdapter {
        final int PAGE_COUNT = 100;
        final int REAL_PAGE_COUNT = 3;
    
        public YourPagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public Fragment getItem(int position) {
            while (position > REAL_PAGE_COUNT - 1) {
                position = position - REAL_PAGE_COUNT ;
            }
    
            switch (position) {
                case 0:
                    return FirstFragment.newInstance(position);
                case 1:
                    return SecondFragment.newInstance(position);
                case 2:
                    return ThirdFragment.newInstance(position);
            }
            return null;
        }
    
        @Override
        public int getCount() {
            return PAGE_COUNT;
        }
    }
    

提交回复
热议问题