-
-
Save moizest89/773082dba9c4af75fa1c1d4b9200314c to your computer and use it in GitHub Desktop.
Utility class that helps with fragment manipulation
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.Fragment; | |
import android.support.v4.app.FragmentManager; | |
/** | |
* Utility class that helps with fragment manipulation. | |
*/ | |
public class FragmentUtils { | |
/** | |
* Adds a fragment into the desired container. | |
* | |
* @param manager Fragment Manager | |
* @param containerId Id of the container | |
* @param fragment Fragment to be added | |
* @param tag Fragment tag | |
*/ | |
public static void addFragment(FragmentManager manager, int containerId, Fragment fragment, String tag) { | |
if (!manager.isStateSaved()) { | |
manager.beginTransaction() | |
.add(containerId, fragment, tag) | |
.commit(); | |
} | |
} | |
/** | |
* Replaces the container content with the desired fragment. | |
* | |
* @param manager Fragment Manager | |
* @param containerId Id of the container | |
* @param fragment Fragment that will replace the current content | |
* @param tag Fragment tag | |
*/ | |
public static void replaceFragment(FragmentManager manager, int containerId, Fragment fragment, String tag) { | |
if (!manager.isStateSaved()) { | |
manager.beginTransaction() | |
.replace(containerId, fragment, tag) | |
.addToBackStack(tag) | |
.commit(); | |
} | |
} | |
/** | |
* Removes a fragment by tag | |
* | |
* @param manager Fragment Manager | |
* @param tag Fragment tag | |
*/ | |
public static void removeFragment(FragmentManager manager, String tag) { | |
Fragment fragment = manager.findFragmentByTag(tag); | |
if (!manager.isStateSaved() && fragment != null) { | |
manager.beginTransaction().remove(fragment).commit(); | |
} | |
} | |
/** | |
* Returns a fragment of the specified type if found in the fragment manager and is instance of the desired type, null otherwise. | |
* | |
* @param manager Fragment Manager | |
* @param fragmentClass Fragment type | |
* @param tag Fragment tag | |
* @param <T> Fragment type | |
* @return Fragment of T type | |
*/ | |
public static <T> T getFragmentByTag(FragmentManager manager, Class<T> fragmentClass, String tag) { | |
Fragment fragment = manager.findFragmentByTag(tag); | |
if (fragment != null) { | |
if (fragment.getClass().isAssignableFrom(fragmentClass)) { | |
return fragmentClass.cast(fragment); | |
} else if (fragment.getClass().getSuperclass().isAssignableFrom(fragmentClass)) { | |
return (T) fragment; | |
} | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment