在ViewHolder中添加item点击事件接口(自定义

Posted Calo-missile

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在ViewHolder中添加item点击事件接口(自定义相关的知识,希望对你有一定的参考价值。

在Adapter中定义接口并提供回调
static class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

private List<String> mList;
private Context mContext;
private OnItemClickListener mOnItemClickListener;

public HomeAdapter(List<String> list, Context context) {
mList = list;
mContext = context;
}
//在里面实现具体的点击响应事件,同时传入两个参数:view和postion
public interface OnItemClickListener{
void onItemClick(View view, int position);

void onItemLongClick(View view, int position);
}

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.mOnItemClickListener = onItemClickListener;
}


public void removeData(int position) {
mList.remove(position);
notifyDataSetChanged();
}


@Override
public HomeAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder holder = new MyViewHolder(LayoutInflater.from(mContext).inflate(R.layout.myrecy_item,
parent, false));
return holder;
}

//对item控件进行点击事件的监听并回调给自定义的监听
@Override
public void onBindViewHolder(final HomeAdapter.MyViewHolder holder, int position) {
holder.mTextView.setText(mList.get(position));
if (mOnItemClickListener != null) {
holder.mTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos = holder.getLayoutPosition();//当前Item列数
mOnItemClickListener.onItemClick(holder.mTextView, pos);
}
});
holder.mTextView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
int pos = holder.getLayoutPosition();
mOnItemClickListener.onItemLongClick(holder.mTextView, pos);
return false;
}

});
}
}

@Override
public int getItemCount() {
return mList.size();
}

class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_item);
}
}
}

在Main中的使用:
private void setLister() {//事件监听
mAdapter.setOnItemClickListener(new HomeAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(MyRecyclerActivity.this, "点击了第" + (position + 1) + "条", Toast.LENGTH_SHORT).show();
}

@Override
public void onItemLongClick(View view, final int position) {
new AlertDialog.Builder(MyRecyclerActivity.this)
.setTitle("确定要删除吗?")
.setNegativeButton("取消", null)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mAdapter.removeData(position);
}
}).show();
}
});
}
 

以上是关于在ViewHolder中添加item点击事件接口(自定义的主要内容,如果未能解决你的问题,请参考以下文章

Android:RecyclerView中添加Item点击事件

从头开始学 RecyclerView 添加item点击事件

RecyclerView的Item的单击事件

Listview与Recycleview的区别

AdapterViewFlipper 添加item点击事件

AdapterViewFlipper 添加item点击事件