How to prevent the addition of a fragment more than once?

Generally, for adding the fragment to a layout of the user interface element is used, for example a button. If the user repeatedly presses the button several times very quickly, it may happen that the fragment is added several times, causing various problems.

How can this be prevented?

+4
source share
1 answer

I created a helper method, which ensures that the fragment is added only if it does not 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(); } } 

Simply calling itself of Activity or another fragment:

 addFragmentOnlyOnce(getFragmentManager(), myFragment, "myTag"); 

It works with both android.app packages. *, And so with android.support.app packages. *.

+11
source

All Articles