我有一项活动。此活动有一个视图寻呼机。此viewpager有五个页面,这些页面在其内容中打开一个片段。例如,当我在第一页中打开两个片段然后在第二页中打开一个片段时,会出现问题。我回到第一页。我单击工具栏中的后退按钮。我使用popBackStack()
代码删除当前可见的片段。
但它删除了所有后台。我该如何解决这个问题?
getSupportFragmentManager().popBackStack(str,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
我的算法:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if(getSupportFragmentManager() != null){
int count = getSupportFragmentManager().getBackStackEntryCount();
Log.i("Fragment Stack Count : ", count+"");
if (count <= 0) {
super.onBackPressed();
} else {
checkBackStack();
}
}
}
private void checkBackStack(){
Log.i("BackStack", "Home Activity Count > 0");
FragmentManager fm= getSupportFragmentManager();
if(fm.getBackStackEntryCount() > 0){
Log.i("BackStack", "Count > 0");
for(int i = (fm.getBackStackEntryCount()-1) ; i >= 0 ; i--){
FragmentManager.BackStackEntry backStackEntry = fm.getBackStackEntryAt(i);
String str= backStackEntry.getName();
Log.i("BackStack", " Name : "+str);
BaseMenuFragment fragment= (BaseMenuFragment) fm.findFragmentByTag(str);
if(((ViewGroup) fragment.getView())!= null && ((ViewGroup) fragment.getView().getParent()) != null){
int contentId = ((ViewGroup) fragment.getView().getParent()).getId() ;
if(contentId == frames[viewPager.getCurrentItem()]){
Log.i("BackStack", "equals = true");
getSupportFragmentManager().popBackStack(str, FragmentManager.POP_BACK_STACK_INCLUSIVE);
return;
}
}
}
}
}