Changing viewPager swipe direction

后端 未结 4 833
醉话见心
醉话见心 2020-12-29 12:47

I\'m using TabLayout and viewPager with an option to swipe the viewPager to the left or right in order to navigate between pages.

My problem is, that my application

4条回答
  •  余生分开走
    2020-12-29 13:18

    i know it's late but this is a smart question. as @CommonsWare said it's the matter of reversing the order of items in getItem() method in page adapter. but this isn't enought. as you reverse the order in getitem() method you should also NOT reverse the order in getPageTitle() method. something like this:

    public static class AppSectionsPagerAdapter extends FragmentStatePagerAdapter {
            public AppSectionsPagerAdapter(FragmentManager fm) {
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return new page1();
                    case 1:
                        return new page2();
                    case 2:
                        return new page3();
                }
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "page 3 title";
                    case 1:
                        return "page 2 title";
                    case 2:
                        return "page 1 title";
                    }
            }
    
            @Override
            public int getCount() {
                return 3;
            }
        }
    

    now comes the tricky part. you should use this simple method which converts zero based index order reversed using max index and current index.

    public int calculateReverse(int maxIndex,int currentIndex){
            return maxIndex-currentIndex;
        }
    

    than you should use this method in onTabSelected() like this: be aware you should use your own max index:

    @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            mViewPager.setCurrentItem(calculateReverse(2,tab.getPosition()));
        }
    

    the second part is to change page listener on page adapter. once again you should use your own max index number:

    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    actionBar.setSelectedNavigationItem(calculateReverse(2,position));  // reversing the tab selection
                }
            });
    

    i tried to be as descriptive as i can. hope this helps :)

提交回复
热议问题