'Android- replacing a fragment inside fragment container (containing multiple fragments) replaces the whole container rather than that one fragment
I have a fragment container, which contains multiple other fragments, but when I am trying to replace one of the fragments inside the fragment container(to reload that fragment), the fragment does get replaced but instead of only that particular fragment getting replaced the whole container is getting replaced by that fragment and even when navigating to other fragments only that fragment is showing up.
I only want to replace one particular fragment present in the container not the whole container.
The fragment I want to replace is TroubleshootFragment. The code I am using to replace the fragment is :
val newfrag = TroubleshootFragment.newInstance()
val ftr = (this.activity)?.supportFragmentManager?.beginTransaction()
?.replace(R.id.container, newfrag)?.commit()
The xml file for container is :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rootView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background_image"
tools:context=".view.HomeActivity">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottom_navigation"
android:layout_below="@id/logoImageView"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_main" />
The xml file for the fragment is :
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_main.xml"
app:startDestination="@id/aboutFragment">
<fragment
android:id="@+id/troubleshootFragment"
android:name="com.p.b.view.fragment.TroubleshootFragment"
android:label="Troubleshoot"
tools:layout="@layout/troubleshoot_layout">
<action
android:id="@+id/action_troubleshootSuccessFragment"
app:destination="@id/troubleshootSuccessFragment" />
</fragment>
I have tried the following code as well :
val ftr = (this.activity)?.supportFragmentManager?.beginTransaction()
?.replace(R.id.troubleshootFragment, newfrag)?.commit()
but this causes the app to crash, then how should I replace the fragment so that only Troubleshoot Fragment gets replaced and not the whole container containing other multiple fragments?
Edit : The log shows this :
I/FragmentNavigator: Ignoring navigate() call: FragmentManager has already saved its state when trying to navigate to other fragments.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
