标签: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();
}
});
}
标签:button 接口 change lis inf class end 添加 extend
原文地址:http://www.cnblogs.com/banzhuan/p/7467007.html