typeof programmer
typeof programmer

Reputation: 1609

Android How back button returns previous fragment?

I have 4 fragments in a FragmentPagerAdapter.

When I am in the 4th fragment and press the back button, it can be returned to previous fragment, it may be the 3rd or 2nd fragment.

But If the previous one is the 3rd one, the app will automatically exit after clicking the back button. What I want is the app can stay on the 3rd fragment after user click the back button on the 4th fragment without automatically exiting. The reason why it happens is because that the two neighbored fragments will taking actions synchronously when user click back button.

How to implement it? Thx.

 public void onBackPressed() {
        moveTaskToBack(true);

        System.out.println(123456);

        ViewPager mViewPager = (ViewPager) this.findViewById(R.id.pager);

       App atp =  this.getApplication();
        int count = atp.getFragmentStack().size();
        if (count == 0) {

            //additional code
        } else {


            mViewPager.setCurrentItem(2);


        }
    }

UPDATES(answering comment 1): My app use FragmentPagerAdapter , so I want to use

ViewPager mViewPager = (ViewPager) this.findViewById(R.id.pager); mViewPager.setCurrentItem(2);

to chang the fragment. Commit does not work, I also need to change the selection bar.

Upvotes: 2

Views: 932

Answers (1)

GIGAMOLE
GIGAMOLE

Reputation: 1266

You need to add to back stack your fragments or replace:

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(here_your_fragment);
    //OR ADD
    //fragmentTransaction.add(here_your_fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit(); 

So for you solution is:

In activity create variable

public int fragmentPosition;

Then, put the value of your activity or fragment into your adaper. In method where your fragments instantiate or gets pass the position of your fragment to the value of fragmentPosition, like this

yourActivityOrFragment.fragmentPosition = position;

And after that, in method onBackPressed() check for position of fragments

public void onBackPressed() {
    if (fragmentPosition == 3) {
         finish();
    } else {
         super.onBackPressed();
    }
}

Upvotes: 2

Related Questions