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

后端 未结 3 1553
独厮守ぢ
独厮守ぢ 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:35

    This is how I do it..

    With FragmentA.java and any other fragments.

    Replace your fragment with its class name as tag:

    private void showFragment(Fragment fragment){
            if(fragment != null){
                getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment,fragment.getClass().getSimpleName()).commit();
            }
        }
    

    Now in onBackPressed():

    @Override
        public void onBackPressed()
        {
    if(getSupportFragmentManager().findFragmentByTag("FragmentA") == null)
                showFragment(new FragmentA());
            else
                super.onBackPressed();
        }
    

提交回复
热议问题