Skip to content

Instantly share code, notes, and snippets.

@beta
Last active August 2, 2016 06:51
Show Gist options
  • Save beta/1e4b3679300a3e8ae155 to your computer and use it in GitHub Desktop.
Save beta/1e4b3679300a3e8ae155 to your computer and use it in GitHub Desktop.
Switching fragments
// Blablabla
/**
* Loads and switches to a new fragment.
* If a fragment with {@code tag} has already been loaded and was detached from the container,
* this method will detach the current fragment and reattach the fragment back again, instead
* of creating a new instance of the target fragment.
*
* @param cls {@code Class} of the new fragment
* @param tag a tag to identify a fragment
*/
private void switchFragment(Class<? extends BaseFragment> cls, String tag) {
Fragment oldFragment = fragmentManager.findFragmentById(R.id.container);
// Check if the target fragment is already visible.
if (oldFragment != null && oldFragment.getTag().equals(tag)) {
return;
}
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (fragmentManager.findFragmentById(R.id.container) != null) {
for (Fragment fragment : fragmentManager.getFragments()) {
if (fragment != null) {
transaction.detach(fragment);
}
}
}
if (fragmentManager.findFragmentByTag(tag) != null) {
// The target fragment has been loaded before.
transaction.attach(fragmentManager.findFragmentByTag(tag));
} else {
// Create a new instance of the fragment.
Fragment fragment = Fragment.instantiate(this, cls.getName());
// Set required fields and listeners for the fragment.
// The listener interfaces are defined in the BaseFragment.
/*
((BaseFragment) fragment).setContext(this);
((BaseFragment) fragment).setOnTitleChangedListener(this);
((BaseFragment) fragment).setOnAppBarLoadedListener(this);
*/
transaction.attach(fragment).add(R.id.container, fragment, tag);
}
transaction.commit();
}
// Blablabla
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment