Abhishek Soni Abhishek Soni -3 years ago 113
Android Question

Defining a RecyclerView's onCLickListener in an Activity

A RecyclerView is different from a ListView because it doesn't offer an onItemCLickListener class to handle click events.

This can be tackled if not a lot is happening behind the scenes when an item is clicked, by defining an onClickListener in the ViewHolder.

What if the text or whatever that has to be passed to the next Activity doesnt really exist in the views that the ViewHolder has access to, but is rather a part of the Activity which has the RecyclerView?

In that case, the onClickListener must be implemented inside the activity so that the text can be forwarded. It is possible.

  1. One way is to add an Invisible View holding that text, and then doing what has been done before; implementing onClickListener in the Adapter.

  2. Pass that text, somehow, to the Adapter.

How can "2." be implemented?

Answer Source

Write a public function in your activity like:

public void onClickCalled(String anyValue) {
    // Call another acitivty here and pass some arguments to it.

Now in your adapter's onClick funciton

public void onClick(View view) {
    ((YouActivityClass) context).onClickCalled("your argument here");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download