Skip to content

Instantly share code, notes, and snippets.

@vodamiro
Last active July 17, 2018 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vodamiro/a42df0e82d0789d62403189797a7e4a1 to your computer and use it in GitHub Desktop.
Save vodamiro/a42df0e82d0789d62403189797a7e4a1 to your computer and use it in GitHub Desktop.
Android - Switching fragments without recreating their instances - Kotlin Extension
...
sealed class Section
object Home : Section()
object Settings : Section()
...
private fun changeSection(section: Section) {
if (currentSection == section) {
return // nothing to do
}
currentSection = section
when (section) {
is Home -> supportFragmentManager.switchFragmentTo(R.id.fragment_container, "HOME") { HomeFragment() }
is Settings -> supportFragmentManager.switchFragmentTo(R.id.fragment_container, "SETTINGS") { SettingsFragment() }
}
}
...
package cz.mvoda.ext
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
/**
* Shows a Fragment according to the tag. If given fragment doesn't exist yet, then it's created
* and added with given tag.
*/
fun FragmentManager.switchFragmentTo(container: Int, tag: String, fragmentFactory: () -> Fragment) {
var existing = findFragmentByTag(tag)
if (existing == null) {
// Not existing -> create new fragment instance and add it
existing = fragmentFactory()
beginTransaction().add(container, existing, tag).commit()
} else if (!existing.isVisible) {
// Added but not visible -> show fragment
beginTransaction().show(existing).commit()
} else {
// Visible -> Nothing to do
return
}
// Hide all other fragments
fragments.filter { it.isVisible && it !== existing }.forEach { beginTransaction().hide(it).commit() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment