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
Conceptually a ViewModel strikes me as the wrong place to launch a Dialog from. To do it more cleanly I would pass the RecyclerView.ViewHolder into the layout, and have a method on the ViewHolder that triggers a custom listener on your RecyclerView.Adapter. Then whoever subscribes to that listener (Activity/Fragment) can launch the Dialog. May seem a little roundabout, but I don't think a ViewModel of a list item should have knowledge or control of its environment.
Here is an example. This is a general pattern for handling RecyclerView item clicks with data binding and a ViewModel. This is not a complete example, just the code to highlight this specific pattern.
Layout:
Adapter:
See the Variables section of the official documentation of the Data Binding Library. There you find a variable
context
you can use.Basically you could just pass it to another variable like the
viewModel
to show the dialog from there.So you can use the context of item for example
itemView.getContext()
to showAlertDialog
The hint from Bayoudh led me in the right direction, but I'm posting this to put the pieces together. Below is a cardview that is clickable. Since my
ViewModel
holds no reference to the activity we have to pass the view in question as a parameter.The
android:onClick="@{(view) -> viewModel.onClick(view)}"
statement takes the current view as a parameter so you can use it in the ViewModel to get context withview.getContext()
as Bayoudh states.