Android Switch Fragment Without Losing Ui State (Kotlin)

February 27, 2019
Show and Hide Fragment

Whenever you replace a fragment, the UI state (EditText's text, RecyclerView's position, etc.) shall be lost unless you save/restore state by overidding onSaveInstanceState(Bundle outState) and onActivityCreated(Bundle savedInstanceState). For temporary state storage, you can use ViewModel.

Another alternative is to show/hide the fragment, which shall maintain the UI state but it will probably consume more memory.

private fun loadFragment(itemId: Int) {
    val tag = itemId.toString()
    var fragment = supportFragmentManager.findFragmentByTag(tag) ?: when (itemId) { -> {
        } -> {
        } -> {
        else -> {

    if (fragment != null) {
        val transaction = supportFragmentManager.beginTransaction()

        if (viewModel.lastActiveFragmentTag != null) {
            val lastFragment = supportFragmentManager.findFragmentByTag(viewModel.lastActiveFragmentTag)
            if (lastFragment != null)

        if (!fragment.isAdded) {
            transaction.add(, fragment, tag)
        else {

        viewModel.lastActiveFragmentTag = tag

NOTE: ViewModel is required to store lastActiveFragmentTag, else the state is lost upon configuration change/screen rotation.

NOTE: To show/hide fragment in the Android BottomNavigationView With Fragment (Kotlin) example.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.