简体   繁体   中英

How can I fix the back navigation with fragments?

I have a problem implementing the back navigation.

Activity A1 starts Activity A2 . A2 contains a full screen fragment:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >

    <!-- fragment goes here -->

</RelativeLayout>

in A2 's onCreate() I load the fragment F1 in the container above:

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    setContentView(R.layout.activity_main);
    replaceFragment(new AccountHomeFragment());
}

public void replaceFragment(Fragment f){
     FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
     fragmentTransaction.replace(R.id.fragment_container, f);
     fragmentTransaction.addToBackStack(f.getClass().getSimpleName());
     fragmentTransaction.commit();
}

And at some point the user clicks on a button and the F1 is replaced by F2 . The problem is when the user clicks on the back button:

  • 1st click: nothing happens
  • 2nd click: goes from F2 to A1 ( F1 skipped)

What I expect

  • 1st click: F2 -> F1
  • 2nd click: F1 -> A1

I have noticed that if I press back before F1 is replaced by F2:

  • 1st click: F1 ->blank screen
  • 2nd click: blank screen-> A1

I think your problem may be caused by adding your first fragment to the backstack as well. In your onCreate you call replaceFragment which adds it automatically. Just add the fragment manually without the addToBackStack call and use the replaceFragment function for all subsequent fragment transactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM