前言:
RecyclerView并没有像ListView那样提供了OnItemClick,OnItemLongClick等事件回调接口,所以,我们需要自己写接口去进行实现。
正题
①、创建接口类OnRecyclerViewClickListener
/**
* RecyclerView条目点击接口
* Created by kang on 2018/9/19.
*/
public interface OnRecyclerViewClickListener {
void onItemClickListener(View view);
void onItemLongClickListener(View view);
}
②、RecyclerView的Adapter中处理接口
- Adapter中创建方法setItemClickListener()
private OnRecyclerViewClickListener listener;
public void setItemClickListener(OnRecyclerViewClickListener itemClickListener) {
listener = itemClickListener;
}
- 在Adapter中onCreateViewHolder()方法中将listener注册为Click回调监听
@Override
public FirstViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_first,null);
FirstViewHolder viewHolder = new FirstViewHolder(view);
//接口回调
if(listener != null){
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onItemClickListener(v);
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
listener.onItemLongClickListener(v);
return true;
}
});
}
return viewHolder;
}
- 索引可以通过RecyclerView.getChildAdapterPosition获取到当前点击的Item的列表索引
int position = recyclerView.getChildAdapterPosition(view);
③、在Activity或Fragment中使用
FirstViewAdapter adapter = new FirstViewAdapter(context,strings);
recyclerView.setLayoutManager(new GridLayoutManager(context,2));
//添加Android自带的分割线
recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(adapter);
adapter.setItemClickListener(new OnRecyclerViewClickListener() {
@Override
public void onItemClickListener(View view) {
int position = recyclerView.getChildAdapterPosition(view);
switch (position){
case 0:
startActivity(new Intent(context,MainActivity.class));
break;
case 1:
startActivity(new Intent(context,BottomNavigationActivity.class));
break;
case 2:
startActivity(new Intent(context,TopTabActivity.class));
break;
case 3:
startActivity(new Intent(context,ListActivity.class));
break;
case 4:
startActivity(new Intent(context,RecyclerViewActivity.class));
break;
case 5:
startActivity(new Intent(context,RefreshAndLoadMoreActivity.class));
break;
case 6:
startActivity(new Intent(context,TabStopActivity.class));
break;
case 7:
startActivity(new Intent(context,FragmentAndRecyclerActivity.class));
break;
}
}
@Override
public void onItemLongClickListener(View view) {
}
});