How to replace fragment C with fragment A when back button is pressed?

后端 未结 3 1554
独厮守ぢ
独厮守ぢ 2021-01-30 11:02

My scenario : Activity 1 consists of Fragments A-> B-> C. All the fragments are added using this code :

        FragmentManager fm = getSupportFragmentManager()         


        
3条回答
  •  离开以前
    2021-01-30 11:22

    You need to do 2 things - name the FragmentTransaction from A->B and then override onBackPressed() in your containing activity to call FragmentManager#popBackStack (String name, int flags) when you are on Fragment C. Example:

    Transition from A->B

    getSupportFragmentManager()
      .beginTransaction()
      .replace(R.id.container, new FragmentB(), "FragmentB")
      .addToBackStack("A_B_TAG")
      .commit();
    

    Transition from B->C will use a similar transaction with "FragmentC" as its tag.

    Then in your containing Activity override onBackPressed():

    @Override
    public void onBackPressed() {
      if (getSupportFragmentManager().findFragmentByTag("FragmentC") != null) {
        // I'm viewing Fragment C
        getSupportFragmentManager().popBackStack("A_B_TAG",
          FragmentManager.POP_BACK_STACK_INCLUSIVE);
      } else {
        super.onBackPressed();
      }
    }
    

提交回复
热议问题