0

I have fragment which contain two dialog fragments i.e (Fragment A -> (Navigate) -> (Dialog A, DialogB) I want to share data between these fragments I tried this way mentioned in developer android Share data between a parent and child fragment

class ListFragment: Fragment() {
    // Using the viewModels() Kotlin property delegate from the fragment-ktx
    // artifact to retrieve the ViewModel
    private val viewModel: ListViewModel by viewModels()
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        viewModel.filteredList.observe(viewLifecycleOwner, Observer { list ->
            // Update the list UI
        }
    }
}

class ChildFragment: Fragment() {
    // Using the viewModels() Kotlin property delegate from the fragment-ktx
    // artifact to retrieve the ViewModel using the parent fragment's scope
    private val viewModel: ListViewModel by viewModels({requireParentFragment()})
    ...
}

When I use it in my case is not working and the views in the parent fragment are not changing when I modify data in the child fragment Also when I logged the view models I found that each view model have its own Id as shown below. Any way to deal with this problem or clear explanation to this.

enter image description here

enter image description here

  • 1
    Can you show where you add your `ChildFragment`? Did you already confirm that `requireParentFragment()` is actually your `ListFragment`? – ianhanniballake Nov 09 '22 at 18:25
  • no, how I can do it another word how to specify that ListFragment is the parent fragment and the the others are child fragments – labed AbdelJalil Nov 09 '22 at 18:28
  • did you consider using requireActivity() and have the view model scoped to the activity instead? that way you're not dependent on the parent fragment. – Greg Moens Nov 09 '22 at 18:35
  • yes I consider using requireActivity() but I don't want to be scoped to the activity scope. – labed AbdelJalil Nov 09 '22 at 19:01
  • I think you're going to need to post some of your actual code, not the example from the Android documentation. Can't tell you where you're going wrong if we can't see what you're doing! – cactustictacs Nov 09 '22 at 22:51

0 Answers0