码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-09-02 18:14:59      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:button   接口   change   lis   inf   class   end   添加   extend   

在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点击事件接口(自定义

标签:button   接口   change   lis   inf   class   end   添加   extend   

原文地址:http://www.cnblogs.com/banzhuan/p/7467007.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!