It's common for a Fragment to be added to a layout when a UI element, such as a button is tapped. If the user taps the button multiple times very quickly, it can happen that the Fragment is added multiple times, causing various issues.
How can this be prevented?
I created a helper method that ensures that the fragment is only added if it doesn't yet exist:
public static void addFragmentOnlyOnce(FragmentManager fragmentManager, Fragment fragment, String tag) {
// Make sure the current transaction finishes first
fragmentManager.executePendingTransactions();
// If there is no fragment yet with this tag...
if (fragmentManager.findFragmentByTag(tag) == null) {
// Add it
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(fragment, tag);
transaction.commit();
}
}
Simple call as such from an Activity or another Fragment:
addFragmentOnlyOnce(getFragmentManager(), myFragment, "myTag");
This works with both the android.app.* and the android.support.app.* packages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With