Issue
I have code below that adds random fragments(First,SecondFragment or ThirdFragment)
private fun addFragment() {
activeFragment = if (activeFragment is FirstFragment) {
SecondFragment()
} else if (activeFragment is SecondFragment) {
ThirdFragment()
} else {
FirstFragment()
}
fragmentTransaction = fragmentManager!!.beginTransaction()
fragmentTransaction?.add(R.id.fragment_container, activeFragment!!)
?.addToBackStack(null)
?.commit()
}
override fun onBackPressed() {
val fragment = fragmentManager?.findFragmentById(R.id.fragment_container)
if (fragment != null) {
Log.d("mytag", "onBackPressed: $fragment")
fragmentManager?.popBackStack()
return
}
super.onBackPressed()
}
In the code above everything works fine. I mean when i press back button it pops the last fragment and shows previous if there any.
But if i remove return statement inside if check (in onBackPressed function), then it pops 2 fragments at once from back stack.(I added onBackStackChangedListener and i can see how many items are left when i pop, so if there are 3 fragments i back stack when i pop it removes 2 fragments and only 1 remains, and then if i click back again, it removes last fragment and also destroys the app)
Solution
The reason you're seeing this behavior is because Fragments already handle the system back button when you use addToBackStack() as part of the super.onBackPressed() call.
That means you don't need to override onBackPressed() at all when using fragments.
Answered By - ianhanniballake
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.