简体   繁体   中英

How can I write a single function that can be re-used by multiple fragments to navigate to a singular destination?

Let's say I have 4 fragments and navigate through them in the order A -> B -> C -> D using a NavController object.

A is my home screen.

I'd like to write a single function called goToA() that can be inherited and called from either B , C or D which navigates to A and clears up the back stack

How do I go about that?

In your BaseFragment just create the function:

protected fun goToA() {
    findNavController().popBackStack(R.id.<id of fragment A in the nav graph here>, false)
}

Now you can call this function from either B , C or D

You can write an extension function for it, defined at the top level outside any classes, that you can call from any of your Fragments:

fun Fragment.goToA() {
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM