Android Switch Fragment Without Losing Ui State (Kotlin)

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.