20

I am using Navigation control (Android Architecture). I used some demo and creating navigation architecture. But the problem is, fragment is getting recalled every time just like: replace fragment when you back from any fragment. So how can I stop this, and how can I set behaviour like Add fragment instead of replace fragment.

I found this problem on web but no one is giving me idea that how to add/replace fragment on navigation control. I tried fragment id to get add fragment approach but not get success.

  1. This is my navigation host xml : I am adding one fragment again and again with logging life cycle.
<?xml version="1.0" encoding="utf-8"?>
<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_graph"
            app:startDestination="@id/questionanswer">

            <fragment
                android:id="@+id/questionanswer"
                android:name="com.softtech360.totalservey.fragment.QuestionAnswer"
                android:label="fragment_first"
                tools:layout="@layout/questionanswer" >
                <action
                    android:id="@+id/action_questionanswer_to_questionanswer"
                    app:destination="@id/questionanswer"

                    />
            </fragment>
</navigation>
  1. I created one button, using this I call every time trigger the function and swap the fragment on host fragment :
val navController = Navigation.findNavController(activity!!,R.id.navhost_fragment)
                            navController.navigate(R.id.questionanswer)
        // using this i swap the fragment on host fragment.
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
chari sharma
  • 462
  • 2
  • 16
  • 1
    Any solution found? – NightFury Nov 15 '19 at 13:18
  • 1
    What is the actual problem you're having? If you're actually [saving your state](https://developer.android.com/guide/fragments/saving-state), then you're fragment will be in exactly the same state as it was in whether you use add or replace. – ianhanniballake Nov 04 '21 at 23:44

3 Answers3

0

Try this:

<action
    android:id="@+id/action_questionanswer_to_questionanswer"
    app:popUpTo="@+id/questionanswer"/>

instead of

<action
    android:id="@+id/action_questionanswer_to_questionanswer"
    app:destination="@id/questionanswer"/>

and then:

navController.navigate(R.id.action_questionanswer_to_questionanswer)

Found this here

SaPropper
  • 463
  • 3
  • 11
0

Try this, without changing destination to popUpTop.

navController.navigate(R.id.action_questionanswer_to_questionanswer)
Ahmad Albatsh
  • 314
  • 1
  • 2
  • 12
0

Try deleting this line

val navController = Navigation.findNavController(activity!!,R.id.navhost_fragment)
                        navController.navigate(R.id.questionanswer)

and run your app again.