0

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.

alfo888_ibg
  • 1,847
  • 5
  • 25
  • 43

1 Answers1

1

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);
                }
            });
MohanadMohie
  • 1,033
  • 1
  • 10
  • 17
  • 1
    You should also note that you should put the next and back buttons in the `Activity` that holds the `ViewPager`, not inside each `Fragment`. – MohanadMohie Oct 14 '16 at 13:51