Techiio-author
Started by Peter DanielsOct 1, 2021

Open
How can i get name of Fragment android kotlin?

2 VIEWES 1 LIKES 0 DISLIKES SHARE
1 LIKES 0 DISLIKES 2 VIEWES SHARE

I need to find out from which fragment the user switched to another fragment. I thought I should use the fragment name, but how do I get that name? Or is my method not very reliable and there are some other options?

P.S.: I use NavHostFragment and Kotlin

1 Replies

Techiio-commentatorDavid Harrison replied 2 months ago0 likes0 dislikes

Instead of the headache of tracking the former fragment with passed-in arguments, you'd apply previousBackStackEntry which returns a NavBackStackEntry that is:

the previous visible entry on the back stack or null if the back stack has less than two visible entries

So, to get the id of the previous destination use: previousBackStackEntry?.destination?.id

For case, assume you've 3 fragments: fragment_a, fragment_b, and fragment_c. And at the fragment_c you need to know from which it's passed

To know the former scrap in fragment_c:

val previousFragment = findNavController().previousBackStackEntry?.destination?.id
previousFragment?.let {
    when (previousFragment) {
        R.id.fragment_a_id ->
            // The previous fragment is Fragment a
        R.id.fragment_b_id ->
            // The previous fragment is Fragment b
        else ->
            // The previous fragment is neither Fragment a nor b
    }
}

You must be Logged in to reply
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance