Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only allow one instance when navigate with NavController

I'm currently using Android Navigation Architecture in my project. It has a feature that can launch any fragment with a shortcut. Currently I'm using NavController to navigate to desired destination when clicking at a shortcut. But when I clicked a shortcuts with multiple times, every time a new instance of the fragment will be created. So, my question is, Is there any way to only accept one instance of a fragment when navigate to it with NavController? I'm googling many times but found nothing. Thanks in advance.

like image 814
Tung Nguyen Thanh Avatar asked Aug 31 '25 04:08

Tung Nguyen Thanh


1 Answers

Add a check before navigating to the destination as it would not add a new instance.

class A: AppCompatActivity {

    fun onCreate(...) {
        // ...While navigating
        if (navController.currentDestination?.id != desiredDestination?.id) {
            navController.navigate(desiredDestination)
        }
        // ...else do nothing
    }
}

Callback from NavController: https://developer.android.com/reference/androidx/navigation/NavController#addOnDestinationChangedListener(androidx.navigation.NavController.OnDestinationChangedListener)

like image 115
Puneet Verma Avatar answered Sep 02 '25 19:09

Puneet Verma