Click item in recyclerview in Android to set events

As mentioned in the previous Android recyclerview introductory tutorial, recyclerview is no longer responsible for the layout and display of item view, so recyclerview does not open onItemClick and other click events for item, which needs to be implemented by developers themselves. There is a demo program running animation at the bottom of the blog.

Here's a GitHub link to the demo.

During the investigation, it was found that some students modified the recyclerview source code to realize item click monitoring, but they thought it was not an elegant solution, and finally decided to write an article on recyclerview.viewholder.

The idea is: because viewholder can get the root layout of each item, if we set a separate onclick listener for the root layout and open it to the adapter, we can not set the itemclicklistener when assembling the recyclerview, but the listener is not set to the recyclerview, but to the adapter.

Let's first look at the code of viewholder:

When constructing the viewholder, the rootview will be passed in as a required parameter, so we only need to get the rootview and bind it to click to listen for events.

The next thing to consider is how to pass in the listener. Interface for listening to click events is set in Demo: myitemclicklistener:

Myitemclicklistener imitates the onitemclicklistener of listview and opens the two parameters of view and position, which is more convenient for developers who are used to using listview. As can be seen from the viewholder code, when the onclick method is executed, getposition () will be called to call back the position of the current item to the listener. Getposition () is the built-in method of viewholder and can be used directly.

As mentioned above, the listener is set on the adapter, so the adapter needs to open related methods:

As mentioned in the previous blog (first acquaintance with Android recyclview), oncreateviewholder of adapter is responsible for instantiating the view of each item, so I pass the listener to viewholder when instantiating the view.

Finally, when assembling recyclerview, set it according to the requirements and click listen:

Demo sets onclick and onlongclicklistener for viewholder. In activity, we implement the interface method and print toast prompt:

The following is the running animation of the demo.

The above is the recyclerview click item setting event in Android introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>