Skip to content

Instantly share code, notes, and snippets.

@AreJay-Smith
Created July 10, 2018 03:32
Show Gist options
  • Save AreJay-Smith/9ebecbb05624f742425c880bcdd74841 to your computer and use it in GitHub Desktop.
Save AreJay-Smith/9ebecbb05624f742425c880bcdd74841 to your computer and use it in GitHub Desktop.
FragmentTransaction without destroying.
val MAP_FRAG_TAG = "mapFragTag"
val LIST_FRAG_TAG = "listFragTag"
fun manageFragmentTransaction(selectedFrag: String) {
when (selectedFrag) {
MAP_FRAG_TAG -> {
if (fragmentManager?.findFragmentByTag(MAP_FRAG_TAG) != null) {
//if the fragment exists, show it.
fragmentManager?.beginTransaction()?.show(fragmentManager?.findFragmentByTag(MAP_FRAG_TAG))?.commit();
} else {
//if the fragment does not exist, add it to fragment manager.
fragmentManager?.beginTransaction()?.add(R.id.container, MapFragment(), MAP_FRAG_TAG)?.commit();
}
if (fragmentManager?.findFragmentByTag(LIST_FRAG_TAG) != null) {
//if the other fragment is visible, hide it.
fragmentManager?.beginTransaction()?.hide(fragmentManager?.findFragmentByTag(LIST_FRAG_TAG))?.commit();
}
}
LIST_FRAG_TAG -> {
if (fragmentManager?.findFragmentByTag(LIST_FRAG_TAG) != null) {
//if the fragment exists, show it.
fragmentManager?.beginTransaction()?.show(fragmentManager?.findFragmentByTag(LIST_FRAG_TAG))?.commit();
} else {
//if the fragment does not exist, add it to fragment manager.
fragmentManager?.beginTransaction()?.add(R.id.container, ListFragment(), LIST_FRAG_TAG)?.commit();
}
if (fragmentManager?.findFragmentByTag(MAP_FRAG_TAG) != null) {
//if the other fragment is visible, hide it.
fragmentManager?.beginTransaction()?.hide(fragmentManager?.findFragmentByTag(MAP_FRAG_TAG))?.commit();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment