0

I currently have the following simple fragment code:

class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }


}

In case I switch to another Fragment I want to save it's current state and restore it when moving back. How can I do that?

I don't want save some variables, but the whole fragment state.

I'm calling the fragment through the code below:

navView.setNavigationItemSelectedListener {


            // Highlight the current selected Item in NavBar
            it.isChecked = true

            // Switch Fragments when user clicks on Items in NavDrawer
            when(it.itemId) {
                R.id.nav_home -> replaceFragment(HomeFragment(), it.title.toString())
                R.id.nav_import -> replaceFragment(ImportFragment(), it.title.toString())
                R.id.nav_export -> replaceFragment(ExportFragment(), it.title.toString())
                R.id.nav_share -> replaceFragment(ShareFragment(), it.title.toString())
            }

            true
        }



        // Default Page is Home
        replaceFragment(HomeFragment(), getString(R.string.home))
Felixkruemel
  • 434
  • 1
  • 4
  • 17
  • 1
    Does this answer your question? [android fragment- How to save states of views in a fragment when another fragment is pushed on top of it](https://stackoverflow.com/questions/6787071/android-fragment-how-to-save-states-of-views-in-a-fragment-when-another-fragmen) – Adinia Mar 02 '22 at 16:02
  • Hey @Adinia Not really as the top voted question does not work for me as I don't understand the meaning of `outState.putInt("curChoice", mCurCheckPosition)` and what to do with it. I just simply want to save the whole fragment as it is. – Felixkruemel Mar 02 '22 at 16:09
  • But that's not the only answer, check [the second top one](https://stackoverflow.com/a/25068471), which also references this one https://stackoverflow.com/a/51909216/469983, which is probably better. – Adinia Mar 02 '22 at 16:31
  • @Adinia I've updated my question to make the calling of the fragments a bit more clear. I seem to be a little dumb right now as I still don't understand on what I need to do. I think I need to change the replaceFragment methods right? – Felixkruemel Mar 02 '22 at 16:41

0 Answers0