我正在开发一个基于NavigationDrawer的应用程序。我的层次结构如下所示:
NavigationDrawer --> 根Fragment(未添加到返回堆栈)--> 详细Fragment(已添加到返回堆栈)
现在,我想在用户按下返回按钮退出应用程序时向用户显示一条消息。以下是我使用的代码:
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else if (getFragmentManager().getBackStackEntryCount() == 0) {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
else
{
super.onBackPressed();
}
}
当我从添加到后台堆栈的详细片段中点击返回按钮时,我会收到警报消息。相反,我希望返回到根片段。
但是,如果我更新代码如下所示,则按下后退按钮将使用户返回到根视图。因此,即使将详细片段添加到后台堆栈中,getFragmentManager().getBackStackEntryCount()也为零。
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else
{
super.onBackPressed();
}
}
这里是我如何从根Fragment调用详细Fragment。
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = SubCategoryListFragment.newInstance(false);
fragmentManager.beginTransaction()
.add(R.id.subCategoryDetails, fragment)
.addToBackStack(null)
.commit();
这是从导航抽屉侧菜单打开的根视图。
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/categoriesRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"/>
<FrameLayout
android:id="@+id/subCategoryDetails"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</FrameLayout>
我在这里做错了什么?实现这个的正确方法是什么?
谢谢。