Home » Android » android – Communicating between Activities and Fragments when using Navigation Architecture Component-Exceptionshub

android – Communicating between Activities and Fragments when using Navigation Architecture Component-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I want to let the host Activity know when something happens in a Fragment. Traditionally, I would have an interface with a callback that the Fragment can call, but now we are ofc using the navigation architecture component.

Is there a way to pass a reference to the host activity down to the fragments or how would I otherwise solve the “Communication between activities and fragments” situation?

Thanks!

How to&Answers:

You can use the LiveData data holder class for such purposes.

Here is an article explaining both Fragment <--> Fragment communication and Activity <--> Fragment communication.

Answer:

you can have a shared ViewModel between your activity and all of your fragments. and use liveData in that viewModel. so when something happens in the fragments you change the liveData and you observe the liveData in the activity

Answer:

You can use a Shared ViewModel (https://developer.android.com/topic/libraries/architecture/viewmodel#sharing)

It would be alive while the activity is and all child fragments can access it.

A LiveData in a Shared ViewModel, for example, could be listened to in all the fragments. If one of those fragments change the data all others would get that change.