Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fragment multiple tabs without remove or replace
class MainActivity : AppCompatActivity() {
private lateinit var swipeFragment: SwipeFragment
private lateinit var favoritesFragment: FavoritesFragment
private lateinit var newsFragment: NewsFragment
private val fragments: Array<out Fragment> get() = arrayOf(swipeFragment, favoritesFragment, newsFragment)
private fun selectFragment(selectedFragment: Fragment) {
var transaction = supportFragmentManager.beginTransaction()
fragments.forEachIndexed { index, fragment ->
if(selectedFragment == fragment) {
transaction = transaction.attach(fragment)
selectedIndex = index
} else {
transaction = transaction.detach(fragment)
}
}
transaction.commit()
}
private var selectedIndex = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
swipeFragment = SwipeFragment()
favoritesFragment = FavoritesFragment()
newsFragment = NewsFragment()
supportFragmentManager.beginTransaction()
.add(R.id.fragment_on_display, swipeFragment, "swipe")
.add(R.id.fragment_on_display, favoritesFragment, "favorites")
.add(R.id.fragment_on_display, newsFragment, "news")
.commitNow()
} else {
selectedIndex = savedInstanceState.getInt("selectedIndex", 0)
swipeFragment = supportFragmentManager.findFragmentByTag("swipe") as SwipeFragment
favoritesFragment = supportFragmentManager.findFragmentByTag("favorites") as FavoritesFragment
newsFragment = supportFragmentManager.findFragmentByTag("news") as NewsFragment
}
val selectedFragment = fragments[selectedIndex]
selectFragment(selectedFragment)
val homeButton = findViewById<ImageButton>(R.id.home_button)
homeButton.setOnClickListener{
selectFragment(swipeFragment)
}
val listButton = findViewById<ImageButton>(R.id.list_button)
listButton.setOnClickListener {
selectFragment(favoritesFragment)
}
val newsButton = findViewById<ImageButton>(R.id.news_button)
newsButton.setOnClickListener {
selectFragment(newsFragment)
}
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
bundle.putInt("selectedIndex", selectedIndex)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment