I have an activity which has a navigation drawer. Navigation drawer has two items named A and B. When A is pressed I am opening Fragment A in the same activity. To display Fragment A, following is my code:
private fun displayView(fragment: Fragment?, title: String) {
if (fragment != null) {
fragmentManager.beginTransaction()
.replace(R.id.framelayout_sliding_activity, fragment, title)
.commit()
this.invalidateOptionsMenu()
}
}
I cannot add this fragment to back stack as it is a requirement. Now Fragment A has two buttons A1 and A2. On click of A1 or A2 I am replacing Fragment A by Fragment A1 or A2. Following is my code:
private fun displayView(fragment: Fragment?) {
if (fragment != null) {
val fragmentManager = fragmentManager
fragmentManager?.beginTransaction()
?.replace(R.id.framelayout_sliding_activity,fragment)
?.addToBackStack(null)
?.commit()
}
}
I need to add Fragment A1 or A2 to backstack as they have a back button in their layout so on the press of back button I can go to Fragment A.
Same case when user presses B on Navigation Drawer which opens Fragment B (cannot be added to backstack) which has two buttons B1 and B2 to open Fragment B1 and B2 (B1 and B2 are added to backstack).
Suppose user presses A1 button of A Fragment and goes to Fragment A1. Now user presses B on Navigation Drawer and presses back button of Android (not of layout), Fragment A and Fragment B then overlaps.
In my on backpressed I have checked:
(fragmentManager.backStackEntryCount != 0 ) -> {
val b = fragmentManager.popBackStackImmediate()
Log.i("Hiii",b.toString())
}
but nothing happens and fragment overlaps. I am using SupportFragmentManager
in all cases.
I have found a solution and the code is working proper but not sure whether this is the correct method or not. Please post your answers if you have a better one.
private fun displayView(fragment: Fragment?, title: String) {
if (fragment != null) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
fragmentManager.beginTransaction()
.replace(R.id.framelayout_sliding_activity, fragment, title)
.commit()
this.invalidateOptionsMenu()
}
}