方法一、直接在Adapter中的onBindViewHolder()方法中实现点击事件
@Override
public void onBindViewHolder(MyViewHolder viewHolder, final int postion) {
viewHolder.textView.setText(mDatas.get(postion));
viewHolder.rootView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(mContext, postion + "", 1000).show();
}
});
}
方法二、
1、自定义一个接口。
public interface OnItemClickListener {
public void onItemClick(View view, int postion);
}
2、在自定义的ViewHolder中实现onClickListenr接口,先声明一个自定义接口的变量,在自定义的ViewHolder的构造函数中添加一个参数-自定义的这个接口,并设置itemview的点击事件,在点击事件中转移到自定义的接口上,传到外面的调用者。
/**
* 自定义的ViewHolder继承自android.support.v7.widget.RecyclerView.ViewHolder
*
* @author raphets
*
*/
public class MyViewHolder extends ViewHolder implements OnClickListener {
TextView textView;
private OnItemClickListener mListener;
public MyViewHolder(View itemView, OnItemClickListener listener) {
super(itemView);
mListener = listener;
itemView.setOnClickListener(this);
textView = (TextView) itemView.findViewById(R.id.textView);
}
@Override
public void onClick(View v) {
mListener.onItemClick(v, getPosition());
}
}
3、在自定义的Adapter中定义一个方法public void setOnItemClickListener(OnItemClickListener listener) {this.mClickListener = listener;}
并暴露给外面的调用者
MyRecylerViewAdapter
public class MyRecylerViewAdapter extends Adapter<MyViewHolder> {
private Context mContext;
private List<String> mDatas;
private OnItemClickListener mClickListener;
public MyRecylerViewAdapter(Context context, List<String> datas) {
this.mContext = context;
this.mDatas = datas;
}
@Override
public int getItemCount() {
return mDatas.size();
}
@Override
public void onBindViewHolder(MyViewHolder arg0, int arg1) {
final int pos = arg1;
arg0.textView.setText(mDatas.get(arg1));
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup arg0, int arg1) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item, arg0, false);
MyViewHolder holder = new MyViewHolder(view,mClickListener);
return holder;
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mClickListener = listener;
}
}
4、在MainActivity中使用
adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(View view, int postion) {
Toast.makeText(MainActivity.this, postion+"", 1000).show();
}
});
方法三、修改RecyclerView源码,在里面实现点击事件,这里我就不说了。
可参考http://blog.csdn.net/jwzhangjie/article/details/36868515