I am doing a NavigationDrawer based application. I have an hierarchy like given below
NavigationDrawer --> RootFragment(Not added to back Stack) --> Detail Fragment (Added to Back Stack)
Now, I am trying to show a message to user when he tries to exit the app by pressing back button. Here is the code I am using for it.
@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();
}
}
When I click back button from the detail fragment, which is added to back stack, I am getting the alert message. Instead I would except to go back to the root fragment.
But, If I update the code like this, pressing the back button takes the user back to the root view. So it looks like getFragmentManager().getBackStackEntryCount() is Zero even if the detailed fragment is added to back stack.
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else
{
super.onBackPressed();
}
}
Here is how I call the detail fragment from the rootFragment.
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = SubCategoryListFragment.newInstance(false);
fragmentManager.beginTransaction()
.add(R.id.subCategoryDetails, fragment)
.addToBackStack(null)
.commit();
Here is the root view which is opened form the navigation drawer side menu.
<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>
What am I doing wrong here? Whats the correct way to implement this?
Thanks.