Created
September 29, 2018 07:13
-
-
Save lvsecoto/26f85aff5b34fd31316408df500116a1 to your computer and use it in GitHub Desktop.
a way to create a singleton dialog fragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.support.v4.app.DialogFragment; | |
import android.support.v4.app.Fragment; | |
import android.support.v4.app.FragmentManager; | |
public class FragmentUtils { | |
private FragmentUtils() {} | |
/** | |
* Use this method to prevent from creating dialog fragment more than one. | |
* | |
* <p>Consider a case that user click button so fast that show more than one dialog fragment. | |
* | |
* @param hostFragment The host fragment of dialog fragment | |
* @param fClass The dialog fragment you want to show singleton | |
* @param <T> The dialog fragment class | |
* @return The dialog fragment instance, it may be new or from dialog fragment manager | |
*/ | |
@SuppressWarnings("unchecked") | |
public static <T extends DialogFragment> T showSingletonFragment( | |
Fragment hostFragment, Class<T> fClass) { | |
// Use class name to tag the fragment | |
String fragmentName = fClass.getName(); | |
FragmentManager fm = hostFragment.getChildFragmentManager(); | |
fm.executePendingTransactions(); | |
// If this dialog fragment isn't in fragment manager, then create new one | |
T fragmentInManager = (T) fm.findFragmentByTag(fragmentName); | |
if (fragmentInManager == null) { | |
fragmentInManager = createFragment(fClass); | |
fragmentInManager.show(fm, fragmentName); | |
} | |
return fragmentInManager; | |
} | |
/** Create fragment from class */ | |
private static <T extends Fragment> T createFragment(Class<T> fClass) { | |
try { | |
return fClass.newInstance(); | |
} catch (IllegalAccessException ignored) { | |
throw new RuntimeException("Failed to create fragment instance"); | |
} catch (InstantiationException ignored) { | |
throw new RuntimeException("Failed to create fragment instance"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment