package com.example.administrator.recyclerview; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class myadapt extends RecyclerView.Adapter { private List<String> list; private Context mcontext; private String Tag="Tag"; public myadapt(List<String> list, Context context) { this.list = list; this.mcontext = context; } public interface OnItemClickListener{ void onItemClick(View v,int pos); }
//设置监听器接口,mainactvity 实现接口 private OnItemClickListener onItemClickListener; public void setOnItemClickListener(OnItemClickListener listener){ onItemClickListener=listener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { LayoutInflater inflater = LayoutInflater.from(mcontext); return new myholder(inflater.inflate(R.layout.item,null),i); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int i) { if(viewHolder instanceof myholder){ final myholder holder=(myholder)viewHolder; holder.getTv().setText(list.get(i)); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onItemClickListener.onItemClick(viewHolder.itemView,i); } }); } } @Override public int getItemCount() { return list.size(); } class myholder extends RecyclerView.ViewHolder { private TextView tv; private int pos; public myholder(View itemView,int pos) { super(itemView); this.pos=pos; Log.i("Tag","myholder"); tv = (TextView)itemView.findViewById(R.id.tv); } public int getPos(){return pos;} public TextView getTv(){ return tv; } } }