I've read other questions. And they don't answer on my question fully. Consider the application built from the template with the main menu on the left side of screen. I need to switch from one menu item to another.
I've implement it like described here with the code
parentFragmentManager.beginTransaction()
.remove(this)
.replace((requireView().getParent() as ViewGroup).getId(), nextFrag, "fileListFragment")
.addToBackStack(null)
.setReorderingAllowed(true)
.commit()
and now it switches... with one "but".
- The active menu item is still "old" one
- Tapping to this "already active old one" item crashes the app with the exception
java.lang.IllegalArgumentException: saveBackStack("ce1065be-e3f1-4520-8f56-1dc07b72657b") must be self contained and not reference fragments from non-saved FragmentTransactions. Found reference to fragment FileListFragment{16f6a37} (5e3e17d1-be7f-4b5c-ad21-1b046b496035 id=0x7f09015c) in BackStackEntry{541bd0d #1 0ee57e90-4b0a-434a-8074-647e6ece56cb} that were previously added to the FragmentManager through a separate FragmentTransaction.
at androidx.fragment.app.FragmentManager.saveBackStackState(FragmentManager.java:2170)
at androidx.fragment.app.FragmentManager$SaveBackStackState.generateOps(FragmentManager.java:3440)
at androidx.fragment.app.FragmentManager.generateOpsForPendingActions(FragmentManager.java:2058)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1748)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
- Tapping on the menu item I expected to be active (that item which I've opened from the code) causes the app crash with similar exception.
So, how do I switch fragments correctly? And what do I wrong?