kotlinfragmentandroid-architecture-navigationandroid-navigation

How to detect if user pressed back button and navigates back in app inside a fragment in Kotlin?


I'm using navigation component, and I wanna detect when user navigates back from fragment B -> A, so I can save a note in room database table created in fragment B before navigating back to fragment A (I'm making a note app, and I wanna save notes just like Google keep note app does).


Solution

  • This should here

    There are a couple of alternatives to the shared view model.

    1. fun navigateBackWithResult(result: Bundle) as explained here https://medium.com/google-developer-experts/using-navigation-architecture-component-in-a-large-banking-app-ac84936a42c2

    2. Create a callback.

    ResultCallback.kt

    interface ResultCallback : Serializable {
        fun setResult(result: Result)
    }
    

    Pass this callback as an argument (note it has to implement Serializable and the interface needs to be declared in its own file.)

    <argument android:name="callback"
                      app:argType="com.yourpackage.to.ResultCallback"/>
    

    Make framgent A implement ResultCallback, fragment B by will get the arguments and pass the data back through them, args.callback.setResult(x)

    Original Post here Original Post here