kozmi55 / Flexible-RecyclerView-with-Databinding

A RecyclerView Adapter that can handle multiple item types without much boilerplate and can be reused on any screen with list content.
Apache License 2.0
28 stars 15 forks source link

Event Click #1

Closed thangtx86 closed 3 years ago

thangtx86 commented 3 years ago

How to implement event onClick listener for item in your sample.

kozmi55 commented 3 years ago

Hi Thang, That's a good question. It depends where do you want to handle the click event.

If you want to handle it in the ItemViewModel, just define a function there and for the root view of the ItemViewModel in the XML add the onClick with DataBinding. An example of this can be seen at the end of the story in the Making an ItemViewModel observable section.

If you want to handle the onClick in the CarListViewModel, you can do the same, just pass a lambda to the ItemViewModel in the constructor and you can call it from the XML.

If you want to handle it in the Fragment for example showing a dialog or navigating to an other screen you would need some kind of observable LiveData, where you push events, when an onClick happens. The fragment would observe that and execute the correct action. Something like this: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

I hope this quick answer can help you. If I will have time I will create a commit in the Github repo demonstrating this, or maybe write a follow up article.

kozmi55 commented 3 years ago

Added examples in the latest commit: https://github.com/kozmi55/felxible-recyclerview-databinding/commit/b4d6537cc10b4d015cebd5f2425f91540a3c0910