Search code examples
androidandroid-fragmentsandroid-navigationandroid-jetpack-navigationandroid-navigationview

Fragment Get Destroyed And Created Again Using Android Jetpack Navigation Controller


I have an activity with three fragments. It will navigate between fragments using navigation controller. But everytime i move to other fragment, the previous fragment destroyed.

When I back (using back key or app bar back button), it will called onCreateView again.

The problem is, I have a method called fetchProducts() that should run once when view created on fragment. Because the fragment alwasy get destroyed, so my fetchProducts always get called again and I dont wanna do that.

Im using viewBinding btw.

Here some of my code:

@AndroidEntryPoint
class HomeMainFragment : Fragment(R.layout.fragment_main_home) {

    private var _binding: FragmentMainHomeBinding? = null
    private val binding get() = _binding!!

    private val viewModel: HomeMainViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentMainHomeBinding.bind(view)
        setupRecyclerView()
        observe()
        goToCreateProductPage()
        fetchProducts()
    }
    
    //...


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}

How to keep the fragment so it will not destroyed? Especially using viewBinding


Solution

  • As this issues: Support multiple back stacks for Bottom tab navigation

    You can use navigation library version 2.4.0-alpha04 and fragment version 1.4.0-alpha04 for back stacks support.

    And yes you should consider using ViewModel to get data that you fetch.