How to resume Fragment from BackStack if exists

前端 未结 6 1044
野的像风
野的像风 2020-11-22 13:29

I am learning how to use fragments. I have three instances of Fragment that are initialized at the top of the class. I am adding the fragment to an activity lik

6条回答
  •  萌比男神i
    2020-11-22 14:24

    I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`

    public void replaceFragment(BaseFragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        final FragmentManager fManager = getSupportFragmentManager();
        BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
        transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
    
        if (fragm == null) {  //here fragment is not available in the stack
            transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
            transaction.addToBackStack(fragment.getFragmentTag());
        } else { 
            //fragment was found in the stack , now we can reuse the fragment
            // please do not add in back stack else it will add transaction in back stack
            transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
        }
        transaction.commit();
    }
    

    And in the onBackPressed()

     @Override
    public void onBackPressed() {
        if(getSupportFragmentManager().getBackStackEntryCount()>1){
            super.onBackPressed();
        }else{
            finish();
        }
    }
    

提交回复
热议问题