通过接口回调的方式:
1.在Adapter中定义点击的接口(也可以不用内部类的形式,单独写一个);
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
2.在recyclerview的adapter中实现点击方法;
package com.cmcc.attendancesystem.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cmcc.attendancesystem.R;
import com.cmcc.attendancesystem.bean.AuditorBean;
import java.util.List;
/**
* Created by 38640 on 2018/3/16.
*/
public class AuditorAdapter extends RecyclerView.Adapter<AuditorAdapter.MyViewHolder> {
private Context mContext;
private List<AuditorBean> mListData;
public AuditorAdapter(Context context, List<AuditorBean> listData) {
this.mContext = context;
this.mListData = listData;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_select_auditor, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
AuditorBean auditorBean = mListData.get(position);
holder.nameTv.setText(auditorBean.getName());
View itemView = ((LinearLayout) holder.itemView).getChildAt(0);
if (mOnItemClickListener != null) {
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getLayoutPosition();
mOnItemClickListener.onItemClick(holder.itemView, position);
}
});
}
}
@Override
public int getItemCount() {
if (mListData != null) {
return mListData.size();
} else {
return 0;
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView nameTv;
public MyViewHolder(View itemView) {
super(itemView);
nameTv = itemView.findViewById(R.id.tv_name);
}
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
private OnItemClickListener mOnItemClickListener;//声明接口
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
}
3.在activity中使用;
auditorAdapter = new AuditorAdapter(this, listData);
auditorAdapter.setOnItemClickListener(new AuditorAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
LogUtils.i(TAG, "点击了:" + position);
}
});
网友评论