Asaf
Asaf

Reputation: 2035

Keeping the back stack after it is being cleared by opening a new activity

In the main activity of my app there is a container that hosts fragments.
When a user clicks a button in the "default" fragment (the first fragment that is displayed), the fragment changes, and so do the actionbar buttons.

One of the buttons in the actionbar of this new fragment open another activity.

In that activity, when a user clicks the back button, the activity closes, and the fragment that was shown in the MainActivity (the fragment that opened the new activity) is still there (which is fine).

However, if a user clicks the back button again, it does not return to the previous fragment. While it does return when the activity does not open.

It turns out that opening the activity clears the backstack (verified by Logging the count from the FragmentManager class), while I'm not quite sure whether this is supposed to behave like this or not, it kinda makes sense. Unfortunately, it is not the behavior I desire.

MainActivity: Fragment A (default) ---> Fragment B ---> Acivity B

Therefore, my question is how can I keep the backstack after the activity resumes, if at all?

I tried searching for similar questions, but all questions I found actually asked how to clear the backstack.

Upvotes: 1

Views: 249

Answers (2)

Palak
Palak

Reputation: 2215

Reading the documentation, there is a way to pop the back stack based on either the transaction name or the id provided by commit. Using the name may be easier since it shouldn't require keeping track of a number that may change and reinforces the "unique back stack entry" logic.

Since you want only one back stack entry per Fragment, make the back state name the Fragment's class name (via getClass().getName()). Then when replacing a Fragment, use the popBackStackImmediate() method. If it returns true, it means there is an instance of the Fragment in the back stack. If not, actually execute the Fragment replacement logic.

private void replaceFragment (Fragment fragment){
  String backStateName = fragment.getClass().getName();

  FragmentManager manager = getSupportFragmentManager();
  boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

  if (!fragmentPopped){ //fragment not in back stack, create it.
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(backStateName);
    ft.commit();
  }
}

Upvotes: 1

Itay
Itay

Reputation: 219

Try that:

@Override
public void onBackPressed() {
    Intent intent = new Intent(A_Acticity.this, B_Activity.class);
    startActivity(intent);
}

Hope it helped! :)

Upvotes: 2

Related Questions