Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload fragment using Navigation Component

I am using the navigation component to load my fragments like given here: https://developer.android.com/guide/navigation/navigation-getting-started

navController = findNavController(R.id.nav_host_fragment)
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.navigation_opt1,
                R.id.navigation_opt2,
                R.id.navigation_opt3,
                R.id.navigation_more
            )
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

I also have a Toolbar at the top with a Spinner. I want to reload/refresh the fragment & its view model when the spinner item is selected. I tried the below code for reloading but it isn't working. Also, I know we should not be using fragmentManager in Navigation Component

val ftr: FragmentTransaction = requireFragmentManager().beginTransaction()
        ftr.detach(this).attach(this).commit()

Any help would be appreciated.

like image 523
varun Avatar asked Sep 11 '20 02:09

varun


2 Answers

sorry for late reply. I am using below code for the same scenario. That might help. call this method in your spinner ItemClick. we have to use popbackstack for avoid adding same fragment again and again.

  private fun refreshCurrentFragment(){
        val id = navController.currentDestination?.id
        navController.popBackStack(id!!,true)
        navController.navigate(id)
    }
like image 67
Harit Dahiya Avatar answered Oct 22 '22 23:10

Harit Dahiya


Yes above answer https://stackoverflow.com/a/66171.. is right

if you want to reload/refresh you current fragment after perform specific operation you have to destroy this current fragment and navigate here again

val fragmentId = findNavController().currentDestination?.id
findNavController().popBackStack(fragmentId!!,true)
findNavController().navigate(fragmentId)
like image 1
Surajkaran Meghwanshi Avatar answered Oct 22 '22 23:10

Surajkaran Meghwanshi