Last active
July 17, 2018 13:24
-
-
Save vodamiro/a42df0e82d0789d62403189797a7e4a1 to your computer and use it in GitHub Desktop.
Android - Switching fragments without recreating their instances - Kotlin Extension
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
... | |
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() } | |
} | |
} | |
... |
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
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