In Fragment on back button pressed Activity is blank

前端 未结 11 1700
囚心锁ツ
囚心锁ツ 2020-11-29 20:04

I have an Activity and many fragments inflated in same FrameLayout



        
11条回答
  •  無奈伤痛
    2020-11-29 20:15

    On a recent personal project, I solved this by not calling addToBackStack if the stack is empty.

        // don't add the first fragment to the backstack
        // otherwise, pressing back on that fragment will result in a blank screen
        if (fragmentManager.getFragments() != null) {
            transaction.addToBackStack(tag);
        }
    

    Here's my full implementation:

        String tag = String.valueOf(mCurrentSectionId);
        FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
        Fragment fragment = fragmentManager.findFragmentByTag(tag);
    
        if (fragment != null) {
            // if the fragment exists then no need to create it, just pop back to it so
            // that repeatedly toggling between fragments doesn't create a giant stack
            fragmentManager.popBackStackImmediate(tag, 0);
        } else {
            // at this point, popping back to that fragment didn't happen
            // So create a new one and then show it
            fragment = createFragmentForSection(mCurrentSectionId);
    
            FragmentTransaction transaction = fragmentManager.beginTransaction()
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .replace(R.id.main_content, fragment, tag);
    
            // don't add the first fragment to the backstack
            // otherwise, pressing back on that fragment will result in a blank screen
            if (fragmentManager.getFragments() != null) {
                transaction.addToBackStack(tag);
            }
    
            transaction.commit();
        }
    

提交回复
热议问题