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) {
        R.id.navigation_home -> {
            TestFragment.newInstance()
        }
        R.id.navigation_dashboard -> {
            Test2Fragment.newInstance()
        }
        R.id.navigation_notifications -> {
            Test3Fragment.newInstance()
        }
        else -> {
            null
        }
    }

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

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

        if (!fragment.isAdded) {
            transaction.add(R.id.fragmentContainer, fragment, tag)
        }
        else {
            transaction.show(fragment)
        }

        transaction.commit()
        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.