Closed thangtx86 closed 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.
Added examples in the latest commit: https://github.com/kozmi55/felxible-recyclerview-databinding/commit/b4d6537cc10b4d015cebd5f2425f91540a3c0910
How to implement event onClick listener for item in your sample.