RecycleView implements the click event of item in Android
RecycleView has now received more and more attention from everyone, because it can replace both listView and GridView. However, RecycleView itself does not have setOnItemClickListener, a click on child items, but we often use RecycleView and hope that his child can be clicked. So how to realize the click event of his item?
First of all, our implementation in:
public class GridViewHolder extends implements OnClickListener{ //Declare MyItemClickListener private MyItemClickListener mListener; public GridViewHolder(View rootView,MyItemClickListener listener) { super(rootView); = listener; (this); } @Override public void onClick(View v) { //If mListener is not empty, implement the method onItemClick in the interface, where getPosition() is the position that gets the clicked position if(mListener != null){ (v,getPosition()); } } //Declare MyItemClickListener interface public interface MyItemClickListener { public void onItemClick(View view,int postion); } }
Finally, implement it in RecyclerViewAdapter:
package ; import ; import ; import ; import ; import ; import ; import .; import ; import ; import ; import ; import ; public class RecyclerViewAdapter extends <GridViewHolder> { private final List<String> labels; private LayoutInflater mLayoutInflater; private Context context; private MyItemClickListener mItemClickListener; public RecyclerViewAdapter(int count, Context context) { = new ArrayList<String>(count); mLayoutInflater = (context); for (int i = 0; i < count; i++) { ((i)); } } @Override public int getItemCount() { return (); } @Override public void onBindViewHolder(GridViewHolder viewHolder, int position) { ((position)); } @Override public GridViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = null; view = (.item_userinfo, parent, false); //Use the constructor to mItemClickListener GridViewHolder holder = new GridViewHolder(view, mItemClickListener); return holder; } /** * Set Item click monitoring * * @param listener */ public void setOnItemClickListener(MyItemClickListener listener) { = listener; } }
Finally in activity
//Set the click event of the item according to the adapter (new MyItemClickListener() { @Override public void onItemClick(View view, int postion) { } });
Thank you for reading, I hope it can help you. Thank you for your support for this site!