我制作了一个使用导航抽屉的简单应用程序,我不喜欢后退按钮的工作方式。如果我从抽屉打开一个片段,然后按下后退按钮就会关闭应用程序。我想按下后退按钮(无论我在哪个片段中)来显示导航面板(就像在Zedge应用程序中一样)。
MainActivity:
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new Audi();
break;
case 2:
fragment = new BMW();
break;
case 3:
fragment = new Volkswagen();
break;
case 4:
fragment = new Kia();
break;
case 5:
fragment = new Volvo();
break;
default:
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(Gravity.START)) {
mDrawerLayout.closeDrawer(Gravity.START);
} else {
super.onBackPressed();
}
}
答案 0 :(得分:0)
在提交之前需要将片段添加到backstack,在.commit()之前添加此代码并再试一次;
.addToBackStack()