Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a fragment from being added multiple times?

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?

like image 301
Tom anMoney Avatar asked Dec 26 '12 07:12

Tom anMoney


1 Answers

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.

like image 83
Tom anMoney Avatar answered Sep 21 '22 00:09

Tom anMoney