3

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!

Dambakk
  • 595
  • 4
  • 20
  • 1
    You don't really want to notify the Activity of anything. If you want to share a scope between multiple Fragments, consider using a common NavGraph, and scope your ViewModel to that NavGraph's NavBackStackEntry (Navigation 2.2.0+). – EpicPandaForce Feb 27 '20 at 00:44
  • @EpicPandaForce Can you show a code sample? – isabsent Apr 24 '20 at 16:11
  • See https://medium.com/androiddevelopers/viewmodels-with-saved-state-jetpack-navigation-data-binding-and-coroutines-df476b78144e – EpicPandaForce Apr 24 '20 at 20:38

3 Answers3

5

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

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

bigahega
  • 405
  • 2
  • 6
  • 1
    That is a very good idea! Thank you! :) I feel like LiveData is only to store data, but why not store a `SnackbarContentModel` and let `MainActivity` observe that data and show a snackbar whenever it changes - which is my situation. :) – Dambakk Feb 18 '20 at 15:41
0

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

Mohsen
  • 1,246
  • 9
  • 22
0

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.