Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android share ViewModel between fragment and dialog fragment?

How to share same viewModel between dialog and dialogFragment? I know that viewModel can be shared in activity scope. But it is too big scope for me.

 private val model: SharedViewModel by activityViewModels()

Unfortunately I don't have in a project navigation component.

like image 720
kkkkk Avatar asked Aug 03 '20 07:08

kkkkk


People also ask

Can a ViewModel be shared between activity and fragment?

In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.

Can two activity share same ViewModel?

You can't share a ViewModel across Activities. That's specifically one of the downsides of using multiple activities as per the Single Activity talk.

How to create a ViewModel from a fragment?

Use activity's scope to create an instance of the ViewModel in fragment so that all the fragments and activity now has a common ViewModel and have access to the same ViewModelStore. If the activity is re-created, it and all its fragments receive the same ViewModel instance that was created by the associated activity.

How do I share data between two fragments in Android?

Data sharing between Fragments. Using SharedViewModel, we can communicate between fragments. If we consider two fragments, both the fragments can access the ViewModel through their activity. Here, one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data.

Why sharedviewmodel object is shared between two fragments?

We have created the object of SharedViewModel which is the same object as we are using the same single activity as an owner. This is the reason it is shared. Notice that we have used the requireActivity () in both the fragments.

How do I communicate between two fragments in Java?

Using SharedViewModel, we can communicate between fragments. If we consider two fragments, both the fragments can access the ViewModel through their activity. Here, one fragment updates the data within the ViewModel which is shared between both the fragments and another fragment observes the changes on that data.


Video Answer


1 Answers

  1. Use childFragmentManager to show DialogFragment

  2. Declare shared ViewModel inside Fragment by

private val sharedViewModel: YourViewModel by viewModels()
  1. Inside DialogFragment declare ViewModel by
private val sharedViewModel: YourViewModel by viewModels(ownerProducer = { requireParentFragment() })
like image 183
Công Hải Avatar answered Oct 23 '22 13:10

Công Hải