Reset fragment by using Navigation Component

Viewed 40

I'd like to have a fun, where the user can restart/reload the fragment on a gesture. For now, I've just added it to some button, for testing purposes. I'm using Navigation Components, and ViewPager 2. I've tried to make an action in navigation graph, to my fragment so it can move to itself, but it doesn't work.

java.lang.IllegalStateException: View androidx.appcompat.widget.AppCompatButton{1649a64 VFED..C.. ...P..ID 1027,823-1335,991 #7f080090 app:id/conversion_converse_btn} does not have a NavController set

Here's some code:

mConvertBtn?.setOnClickListener {
    val test = ConversionDirections.actionTest()
    it.findNavController().navigate(test)
}

Nav graph

<fragment
    android:id="@+id/conversion"
    android:name="com.example.currencyexchange.Fragments.Conversion"
    android:label="label"
    tools:layout="@layout/layout">
    <action
        android:id="@+id/action_test"
        app:destination="@id/conversion" />

What can I do with it? I feel like I've tried every solution that I found, but none was effective.

1 Answers

I've tried to make an action in navigation graph, to my fragment so it can move to itself, but it doesn't work.

This won't work as the fragment already in the back stack, you can't add two fragments with the same id in the back stack.

So, you need to pop it off the back back stack first, and then add it again like:

val id = findNavController().currentDestination!!.id
findNavController().popBackStack(id, true)
findNavController().navigate(id)
Related