我正在使用android應用程序。我面臨的問題就像在後面的堆棧歷史記錄中添加碎片。讓我解釋清楚,我想從片段A導航到片段B,然後使用片段B中的按鈕單擊返回到片段A.上面的場景工作良好,在此導航到片段A後,當我點擊設備中的後退箭頭時導航到片段B.我不希望發生這種情況。給我一個解決方案。我的代碼結構如下:在android中通過片段導航而不將其添加到後臺堆棧
片段A:
.......
FragmentB fragmentB = new FragmentB();
showFragmentOmitStack(fragmentB);
....
public void showFragmentOmitStack(Fragment fragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.container,fragment);//add // replace
transaction.addToBackStack(null);
transaction.commit();
}
片段B:
FragmentA fragmentA = new FragmentA();
showFragment(fragmentA, "FragmentA");
public void showFragment(Fragment fragment, String back_stack_name) {
FragmentManager fragmentManager = thisActivity.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.addToBackStack(back_stack_name);
fragmentTransaction.commit();
}
在我的活動Java文件:
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (getFragmentManager().getBackStackEntryCount() == 0) {
showAlertDialog(Constants.EXIT_APP, Constants.APP_NAME);
} else {
getFragmentManager().popBackStackImmediate();
}
}
}
當您單擊B片段的按鈕,不添加新的片段A,只是彈出堆棧中。你做這件事的方式就是成爲A B A. – ElDuderino