I know there are tons of questions about Fragments and I read many, but it seems I haven't grasped it yet.
My app has 9 Fragments. On one of them, say Fragment X, I am playing media and from there it shows up another Fragment on screen, say Y. To perform that, I thought the best was using replace()
.
My relevant code:
// Button clicked, goes from X to Y
getFragmentManager().beginTransaction()
.replace(R.id.container, fragmentY)
.commit();
When onBackPressed()
is called and fragmentY is the one returned by fragmentManager.findFragmentById(R.id.container)
:
fragmentManager.beginTransaction()
.replace(R.id.container, fragmentX)
.commit();
Expected behavior: it'd remove X and add Y. When going back, it'd remove Y and add X.
What happened: first time I go to Y, Y is shown as expected, but X is still running as I hear the audio playing. When I go back, Y disappears and it seems fine. However, next time I click to go to Y, X is then destroyed (audio stops playing) and the app gets weird, since my ActionBar shows up and it shouldn't. Moreover, I keep a hidden Fragment with a map that gets blank after executing that.
I imagine replace() not only removes the current fragment, but all of the visible fragments. But doing .remove(X).add(Y, "y") does not show my Fragment.
Any help?
EDIT: As it was asked, my Fragment X can be added to the Activity from different points on the app, hence on different ways. They're two:
// If backPressed and current Fragment is A
fragmentTransaction.remove(fragmentA).add(R.id.container, objectFragment).commit();
or
// If backPressed and current Fragment is B (map)
fragmentTransaction.hide(fragmentB).add(R.id.container, objectFragment).commit();
Most of the times I must know where I am coming from and where I'm going, that's why I did not use addToBackStack()
.