4

I have parent Fragment that contains child fragment. Inside child fragment I have ViewPager with fragments. My question is how can I share ViewModel between parent child and fragments in viewpager and makeing Viewmodel visible only on ParentFragment scope?

Rasul
  • 727
  • 7
  • 20
  • You can try this method on fragments inside view pager. By calling this once will give you child fragment that is hosting view pager itself and then on that returned reference you can call this method again to get your parent fragment reference: https://developer.android.com/reference/androidx/fragment/app/Fragment#getParentFragment() – Jeel Vankhede Jan 21 '21 at 07:39
  • check this out https://stackoverflow.com/a/61974340/2235972 – denvercoder9 Jan 22 '21 at 13:46

2 Answers2

2

what do you mean when you say "visible only on ParentFragment scope"?

According Google's document, there is one way that you can share ViewModel. Check this document: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing Shortly, your parent fragment and child fragment will use the same ViewModel. Your parent fragment will call the function of ViewModel to change the data, your child fragment just observer the LiveData of ViewModel.

NhatVM
  • 1,964
  • 17
  • 25
  • My child and parent fragments use the same model. But how can i use the same model inside ViewPager's fragment – Rasul Jan 21 '21 at 07:14
  • 1
    Do you try to use "by activityViewModels()" to get shared ViewModel in ViewPager's fragment? – NhatVM Jan 21 '21 at 07:37
-1

You can place your sharedViewModel inside your Activity. Then you can access it from every fragment which in attached to this activity with this code:

(requireActivity() as MainActivity).viewModel;

With this approach, you can set data from one fragment and observe data from another fragment. So, you enable communication between two fragments.

Setting data:

viewModel.liveDataObject.value = value

Observing data:

viewModel.liveDataObject.observe(viewLifecycleOwner) {}
Matija Sokol
  • 107
  • 6