因为RecyclerView没有点击、长按事件,需要自己写
实现的方式比较多,可以通过adapter中自己去提供回调
废话不多说,直接看代码:
代码语言:javascript复制public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
/**
*定义回调接口
*/
public interface OnItemClickLitener {
void onItemClick(View view, int position);//点击事件
}
/**
* 单击 点击监听事件变量
*/
private OnItemClickLitener mOnItemClickLitener;
/**
* 设置
* @param mOnItemClickLitener
*/
public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
this.mOnItemClickLitener = mOnItemClickLitener;
}
private LayoutInflater mInflater;//布局填充器
private List<Integer> mDatas;//适配器绑定的数据
/**
* 构造函数
*/
public GalleryAdapter(Context context, List<Integer> datats) {
mInflater = LayoutInflater.from(context);
mDatas = datats;
}
/**
*ViewHolder 跟listView里面一样 属性是item 布局里面各个视图控件
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View arg0) {
//这里面可以先找到各个视图控件,
super(arg0);
}
ImageView mImg;
TextView mTxt;
}
@Override
public int getItemCount() {
return mDatas.size();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
//找到对应的布局item
View view = mInflater.inflate(R.layout.activity_index_gallery_item,viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.mImg = (ImageView) view.findViewById(R.id.id_index_gallery_item_image);
return viewHolder;
}
/**
* 该函数用来进行数据填充的,同时如果有监听事件,也在这里面
*/
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
// 布局填充数据
viewHolder.mImg.setImageResource(mDatas.get(i));
// 如果设置了回调,则设置点击事件
if (mOnItemClickLitener != null) {
viewHolder.itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//设置点击事件 具体的调用执行,由当前的adapter实例进行操作
mOnItemClickLitener.onItemClick(viewHolder.itemView, i);
}
});
}
}
}
在对应的activity中adapter实例调用点击事件:
代码语言:javascript复制 mAdapter.setOnItemClickLitener(new OnItemClickLitener()
{
@Override
public void onItemClick(View view, int position)
{
Toast.makeText(HomeActivity.this, position " click",
Toast.LENGTH_SHORT).show();
}
@Override
public void onItemLongClick(View view, int position)
{
Toast.makeText(HomeActivity.this, position " long click",
Toast.LENGTH_SHORT).show();
mAdapter.removeData(position);
}
});
该处代码只展示了 点击事件,长按事件是一样的做法,无非就是多一个方法了:
代码语言:javascript复制 public interface OnItemClickLitener
{
void onItemClick(View view, int position);
void onItemLongClick(View view , int position);
}
然后在onBindViewHolder里面加入设置就可以:
代码语言:javascript复制 viewHolder.itemView.setOnLongClickListener(new OnLongClickListener()
{
@Override
public boolean onLongClick(View v)
{
mOnItemClickLitener.onItemLongClick(viewHolder.itemView, i);
}
});