0

How can I access any of the fragments in backstack when using Android Navigation Component? Let's sat you navigate to Fragment A then to Fragment B and then to Fragment C using Navigation Component. Now you want to access Fragment A or Fragment B instance (without popping any fragments) and set a value to one of its fields. Back in the day, we could do that using findFragmentByTag. But how can you do it now when using Navigation Component?

Harry
  • 323
  • 3
  • 10
  • 1
    That isn't how you should be [communicating with fragments](https://developer.android.com/guide/fragments/communicate) at all. All of the techniques in the documentation work with the Navigation Component. – ianhanniballake Sep 03 '21 at 02:24
  • @ianhanniballake Thank you for your comment and including the link. I believe that I had read this before, but they change the documents every damn day! There was some new things that I learned. Thanks again! – Harry Sep 03 '21 at 19:19

1 Answers1

1

If you want to access the other fragments data in the same activity, using SharedViewModel might be a good idea. You can check the SharedViewModel example.

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

class ListFragment : Fragment() {

    private lateinit var itemSelector: Selector

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        itemSelector.setOnClickListener { item ->
            // Update the UI
        }
    }
}

class DetailFragment : Fragment() {

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
            // Update the UI
        })
    }
}

If you want to see more detail, here is the official documentation for the SharedViewModel.

Isaac Lee
  • 466
  • 1
  • 3
  • 15