RecyclerView 点击事件处理

RecyclerView不像ListView那样,提供了setOnItemClickListener,所以一般情况需要我们自己定义一个接口实现这个功能。我一般会通过Adapter去暴露出来一个接口,便于上层获取位置和点击事件。

public static interface OnItemClickListener {
	void onItemClicked(View v, int postion);
}
private OnItemClickListener onItemClickListener;
public OnItemClickListener getOnItemClickListener() {
	return onItemClickListener;
}

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
	this.onItemClickListener = onItemClickListener;
}
view.setOnClickListener(this);
holder.itemview.setTag(position);
@Override
public void onClick(View view) {
	if (onItemClickListener != null) {
		onItemClickListener.onItemClicked(view, (Integer) view.getTag());
}
}

这样上层就很方便的获取了位置信息,并可以做相对的处理。

RecyclerView recyclerView = new RecyclerView(this);
recyclerView.setLayoutManager(new  LinearLayoutManager(this));
MyAdapter adapter = new MyAdapter();
adapter.setOnItemClickListener(l -> { /*do something you need*/ });
recyclerView.setAdapter(adapter);

Done

Published with Ghost | Moegi