Created
May 13, 2016 09:41
-
-
Save Isabellle/03013868bb95d9c21e2d5d1851854498 to your computer and use it in GitHub Desktop.
Get clicked item and its position in RecyclerView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Based on the link: Why doesn't RecyclerView have onItemClickListener()? and How RecyclerView is different from Listview?, and also @Duncan's general idea, I give my solution here: | |
//define one interface 'RecyclerViewClickListener' for passing message from adapter to Activity/Fragment: | |
public interface RecyclerViewClickListener | |
{ | |
public void recyclerViewListClicked(View v, int position); | |
} | |
//In Activity/Fragment implement the interface, and also pass listener to adapter: | |
@Override | |
public void recyclerViewListClicked(View v, int position){... ...} | |
//set up adapter and pass clicked listener this | |
myAdapter = new MyRecyclerViewAdapter(context, this); | |
//In Adapter and ViewHolder: | |
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ItemViewHolder> { | |
... ... | |
private Context context; | |
private static RecyclerViewClickListener itemListener; | |
public MyRecyclerViewAdapter(Context context, RecyclerViewClickListener itemListener) { | |
this.context = context; | |
this.itemListener = itemListener; | |
... ... | |
} | |
//ViewHolder class implement OnClickListener, | |
//set clicklistener to itemView and, | |
//send message back to Activity/Fragment | |
public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ | |
... ... | |
public ItemViewHolder(View convertView) | |
{ | |
super(convertView); | |
... ... | |
convertView.setOnClickListener(this); | |
} | |
@Override | |
public void onClick(View v) | |
{ | |
itemListener.recyclerViewListClicked(v, this.getPosition()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment