Sweta Jain
Sweta Jain

Reputation: 4334

Can a Dialog have a view model in android?

I need to do an API call from a Dialog. Do I need to go back to the fragment for doing so, or is there any way to refer to the fragment view model?

Upvotes: 3

Views: 5656

Answers (3)

Sweta Jain
Sweta Jain

Reputation: 4334

Yes, it is possible and I was able to do that because class DialogFragment extends Fragment. So I added a view model just like any other fragment.

enter image description here

like below where BaseDialog class extends DialogFragment

enter image description here

Upvotes: 5

Matija Sokol
Matija Sokol

Reputation: 167

You can try with this:

  1. Use interface, implement it in fragment so you have callback funtion.

  2. Pass high ordered function, declare it like this in dialog:

    var click: (() -> Unit)? = null;

    Then you can set it from fragment when you instantiate your dialog.

  3. Use shared view model, for example make view model in your activity and then you can access it from every fragment or dialog like this:

(requireActivity() as MainActivity).viewModel

Like this you can set value in view model variable (liveData often) inside your dialog and observe changes in fragment

Upvotes: 1

rogalz
rogalz

Reputation: 80

I think you can pass a high ordered function to dialog and handle it in fragment using viewModel inside.

Upvotes: -1

Related Questions