Avoid recreating same view when perform tab switching

后端 未结 6 587
一生所求
一生所求 2021-01-30 17:43

Current, I have 2 Fragments, which is switch-able through ActionBar\'s tab.

    getSupportActionBar().setNavigationMode(ActionBar.NAVIG         


        
6条回答
  •  一生所求
    2021-01-30 18:10

    The following solution works for me. It prevents Fragment's onCreateView to be called when switching tabs.

    Activity's onCreate should add all fragments and hide all except the one for the first tab:

    ft.add(R.id.fragment_content, secondTabFragment);
    ft.hide(secondTabFragment);
    ft.add(R.id.fragment_content, firstTabFragment);
    ft.show(firstTabFragment);
    ft.commit();
    currentFragment = firstTabFragment;
    

    Activity's onTabSelected should just hide the current fragment and show the fragment corresponding to the chosen tab.

    ft.hide(currentFragment);
    ft.show(chosenFragment);
    ft.commit();
    currentFragment = chosenFragment;
    

    Beware that changing the device orientation will restart your Activity and then recreate your Fragments. You can avoid that by adding this configChanges in your Manifest:

提交回复
热议问题