1

我在一个活动中有一个框架布局,我想在其中显示不同的片段。我有一个带有 3 个选项的滑动抽屉,每个选项都会导致在框架布局内加载一个片段。目前我使用以下方法来完成此操作:

Fragment nextFragment = determineFragmentToSwitchTo(nextFragmentTag);
transaction.replace(R.id.fragment_container, nextFragment);

第一种方法通过评估 nextFragmentTag 字符串并像这样加载新片段来确定我需要什么片段:

if (fragmentTag.equals(Constants.STUDENTPAGE))
     nextFragment = new StudentFragment();
else if (fragmentTag.equals(Constants.TEACHERPAGE))
     nextFragment = new TeacherFragment();
else if (fragmentTag.equals(Constants.PARENTPAGE))
     nextFragment = new ParentFragment();

显然,这种方法每次都创建一个新片段,并在不保存状态的情况下运行整个片段生命周期。因此,如果我在学生页面上滚动学生列表并切换到父页面,当我返回学生页面时,它会重新加载整个列表(我从服务器获取它)并失去我的位置它。我怎样才能让它保持状态并在管理器中缓存该片段(如果有意义的话)?

4

1 回答 1

1

您可以使用FragmentTransaction's hide(Fragment)andshow(Fragment)方法,例如:

// In the parent Activity 

StudentFragment studentFragment;
TeacherFragment teacherFragment;
ParentFragment parentFragment;
Fragment fragmentOnDisplay;

@Override
protected void onCreate(Bundle savedInstanceState) {

   // Initialize fragmentManager, fragmentTransaction, etc.

   studentFragment = (StudentFragment) fragmentManager.findFragmentByTag(Constants.STUDENTPAGE);
   if (studentFragment == null) {
      studentFragment = new StudentFragment ();
      fragmentTransaction.add(R.id.your_frame_layout, studentFragment, Constants.STUDENTPAGE);
   }

   // repeat the same procedure for the other two fragments     

   // Suppose you want to begin with the teacherFragment on 
   // display - in that case hide the studentFragment and 
   // the parentFragment:             

   fragmentTransaction.hide(studentFragment);
   fragmentTransaction.hide(parentFragment);
   fragmentOnDisplay = teacherFragment;
   fragmentTransaction.commit();
}

现在,当您需要切换片段时,只需hide显示show片段和您需要的片段,例如:

...
fragmentTransaction.hide(fragmentOnDisplay);
fragmentTransaction.show(parentFragment);
fragmentOnDisplay = parentFragment;
fragmentTransaction.commit();
于 2013-08-26T18:41:40.667 回答