Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the recommended way to launch a DialogFragment from a ViewModel?

I have a list objects in a Recyclerview. When long-pressing an item I want to show a dialog with data from the item clicked.

The Recyclerview is using data binding for each item and I am able to display data from the selected item using Log when long-pressing.

When trying to show a dialog, however, you need to get to the Activity, which is not recommended to use in the ViewModel object.

So how can I show the dialog?

Thanks, Ove

like image 608
Ove Stoerholt Avatar asked Mar 14 '17 10:03

Ove Stoerholt


2 Answers

See the Variables section of the official documentation of the Data Binding Library. There you find a variable context you can use.

A special variable named context is generated for use in binding expressions as needed. The value for context is the Context from the root View's getContext(). The context variable will be overridden by an explicit variable declaration with that name.

Basically you could just pass it to another variable like the viewModel to show the dialog from there.

android:onClick="@{v -> viewModel.showDialog(context)}"
like image 189
tynn Avatar answered Oct 24 '22 04:10

tynn


I think using a binding adapter for a recyclerview and put the adapter n ViewModel, then make the viewmodel is the model of fragment and passing adapter for the setAdapter method in xml itself.

like image 38
Mouaz Salah Avatar answered Oct 24 '22 04:10

Mouaz Salah