kkkkk
kkkkk

Reputation: 726

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.

Upvotes: 21

Views: 6711

Answers (1)

Công Hải
Công Hải

Reputation: 5241

  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() })

Upvotes: 35

Related Questions