I am new to Android development and am now confused about strange behavior.
- I have an empty FrameLayout as a fragment container.
- If the user clicks the button for the first time, generates a new fragment and places it inside the container.
- If the user clicks the button later and there will be an existing fragment inside the container, replace the existing one with a new one.
- If the user clicks the back button, remove the fragment inside the container.
Here is my code
public void showFragment(View v) { FragmentA f = new FragmentA(); FragmentManager fm = getSupportFragmentManager(); String tag = f.getFragmentTag();
When the user clicks the button for the first time, he behaves as I expected, adding a new fragment to the container. But the second time the user presses the button while the container still contains the fragment, instead of replacing it, it adds a new one on top of the existing one. So, 2 fragments inside the container, 2 back click to delete the entire fragment.
I found that if I delete the line
ft.addToBackStack();
And recycle the onBackPress () method as shown below, it works again as I expected (1 fragment in the container at a time)
basically manually remove the snippet instead of the popFromBackStack method
private FragmentA currentFragment = null; // to hold the reference to exising fragment, if any. @Override public void onBackPressed() { if (currentFragment != null) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.setCustomAnimations(0, R.anim.slide_out_top); ft.remove(currentFragment); ft.commit(); currentFragment = null; } else { super.onBackPressed(); } }
So my question is:
- replace and addToBackStack not working together?
- or did i do something wrong?
Appreciate all comments and suggestions.
android android-fragments fragmenttransaction
Tar_tw45
source share