Search code examples
androidandroid-viewpagerviewpageandroid-tabbed-activity

why setCurrentItem() of viewPager works for next page and not for previous page?


I am using Tabbed Activity of Android Studio.

I'm moving between the pages swiping but i added 2 views to move next and previous by onclick method but it doesn't work to go back only to go next.

     nextAbitudini.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //it works
                        mViewPager.setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER));
                    }
                });

     backAbitudini.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                       //it doesn't work
                       mViewPager.setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER)-1);
                    }
                });

I'm using FragmentPagerAdapter. It works swiping back.

I put onClick methods inside onCreateview.


Solution

  • Refering to the Tabbed Activity, take a look at the section number as the fragment is initialized. (sectionNumber = position+1).

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }
    

    Therefore, ARG_SECTION_NUMBER-1 refers to the position of the current fragment, ARG_SECTION_NUMBER-2 to the previous, and ARG_SECTION_NUMBER to the next.

    Consequently, your code should be like this:

     nextAbitudini.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //it works
                        mViewPager.setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER));
                    }
                });
    
     backAbitudini.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                       //it doesn't work
                       mViewPager.setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER)-2);
                    }
                });