How can I switch between two fragments, without recreating the fragments each time?

后端 未结 10 1858
孤独总比滥情好
孤独总比滥情好 2020-12-08 00:19

I\'m working on an android application, that uses a navigation drawer to switch between two fragments. However, each time I switch, the fragment is completely recreated.

10条回答
  •  借酒劲吻你
    2020-12-08 00:53

    Same idea as Tester101 but this is what I ended up using.

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
        Fragment oldFragment = fragmentManager.findFragmentByTag( "" + m_lastDrawerSelectPosition );
        if ( oldFragment != null )
            fragmentTransaction.hide( oldFragment );
    
        Fragment newFragment = fragmentManager.findFragmentByTag( "" + position );
        if ( newFragment == null )
        {
            newFragment = getFragment( position );
            fragmentTransaction.add( R.id.home_content_frame, newFragment, "" + position );
        }
    
        fragmentTransaction.show( newFragment );
        fragmentTransaction.commit();
    

提交回复
热议问题