Akhil Pandey
Akhil Pandey

Reputation: 67

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).

Upvotes: 0

Views: 856

Answers (2)

asem elkhouli
asem elkhouli

Reputation: 29

in Activity

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_ESCAPE) {
            onBackPressedDispatcher.onBackPressed()
            //Your code
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //Your code
        }
        return super.onKeyUp(keyCode, event)
    }

Upvotes: 0

timilehinjegede
timilehinjegede

Reputation: 14043

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

Upvotes: 1

Related Questions