我应该在活动中创建每个片段的成员变量吗?
像:
private DemoFragment1 frag1;
private DemoFragment2 frag2;
private DemoFragment3 frag3;
private DemoFragment4 frag4;
private DemoFragment5 frag5;
然后在Activity.onCreate()中我应该实例化所有这些,以便我知道它们都已经启动并且只启动了一次?或者当我去创建它们时,我应该这样做吗?
createFrag1(){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_holder, new DemoFragment1());
fragmentTransaction.commit();
}
答案 0 :(得分:0)
在我的一项活动中,我在WindowsFocusChanged上添加了所有片段(所以我有适当的屏幕测量值):
private void addFragments() {
if(mPassedMachine.getMachineType() == MachineType.ZR7)
addZeroFragment(ANIMATION_TYPE_NONE, false);
else
addLevelFragment(ANIMATION_TYPE_NONE, false);
addHeartRateFragment(ANIMATION_TYPE_NONE, false);
addMaxMinAvgFragment(ANIMATION_TYPE_NONE, false);
addExtraFragment(ANIMATION_TYPE_NONE, false);
}
当我添加片段时,我确保将其添加到片段堆栈中。然后,当我检索片段时,我要么获得现有片段,要么创建一个新片段:
private void addLevelFragment(int animationType, boolean shouldShow) {
String fragmentTag = getFragmentTag();
FragmentTransaction fragmentTransaction = getFragmentTransactionWithAnimation(animationType);
mLevelFragment = (SupplementLevelFragment) getFragmentManager().findFragmentByTag(fragmentTag);
if(mLevelFragment == null) {
mLevelFragment = new SupplementLevelFragment();
Bundle levelBundle = getSupplementBundle(false);
levelBundle.putBoolean(WorkoutSupplementBaseFragment.SUPPLEMENT_CLOCK_COUNT_DOWN, mTimerCountingDown);
levelBundle.putInt(WorkoutSupplementBaseFragment.FRAGMENT_ORIGINAL_TIME, mTotalMinutes);
levelBundle.putInt(SupplementLevelFragment.FRAGMENT_LEVEL, mCurrentLevel);
mLevelFragment.setArguments(levelBundle);
fragmentTransaction.addToBackStack(null);
}
fragmentTransaction.replace(R.id.workout_supplement_fragment_middle_layout, mLevelFragment, fragmentTag);
if(shouldShow == true)
fragmentTransaction.show(mLevelFragment);
else
fragmentTransaction.hide(mLevelFragment);
fragmentTransaction.commit();
fragmentTransaction = null;
}
我这样做是因为我滚动片段并向他们添加数据,即使他们当前没有焦点。