这是我的代码段: 我想最初创建一个新片段,但如果片段已经创建,我想显示前一个片段;
但每次新片段初始化时。
@Override
protected void onCreate(Bundle savedInstanceState) {
.
.
showFragment(FRAGMENT_ADD_DETAILS);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(currentFragment==FRAGMENT_ADD_DETAILS){
finish();
}else{
showFragment(FRAGMENT_ADD_DETAILS);
}
break;
case R.id.menu_action_next:
showFragment(FRAGMENT_INVITE_FRIENDS);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
.
.
return true;
}
private void showFragment(int fragmentType) {
Log.d(TAG,"showFragment : "+fragmentType);
FragmentManager fragmentManager = getFragmentManager();
Fragment prevFragment = fragmentManager.findFragmentByTag(String.valueOf(fragmentType));
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (prevFragment == null) { //create a fresh instance of fragment
Log.d(TAG,"Initialize new fragment");
Fragment newFragment;
if (fragmentType == FRAGMENT_ADD_DETAILS) {
newFragment = new NewDetailsFragment();
} else {
newFragment = new NewInviteFragment();
}
fragmentTransaction.replace(R.id.ant_container_layout, newFragment);
fragmentTransaction.addToBackStack(String.valueOf(fragmentType));
} else {//just reuse the previous fragment
Log.d(TAG,"Re-Using previous fragment");
fragmentTransaction.replace(R.id.ant_container_layout, prevFragment);
}
fragmentTransaction.commit();
}
请帮助!
答案 0 :(得分:2)
您永远不会在片段中添加任何标记,因此您无法使用findFragmentByTag()
找到它们。
替换片段时,而不是
fragmentTransaction.replace(R.id.ant_container_layout, newFragment);
使用接受标记的重载方法:
fragmentTransaction.replace(R.id.ant_container_layout, newFragment, String.valueOf(fragmentType));
您尝试在onCreate()
活动中恢复您的片段,但似乎您还没有保留您的片段。因此它们与活动一起被销毁,并且当再次创建活动时,将创建新的碎片。