1 package com.example.administrator.recyclerview; 2 3 import android.content.Context; 4 import android.support.v7.widget.RecyclerView; 5 import android.view.LayoutInflater; 6 import android.view.View; 7 import android.view.ViewGroup; 8 import android.widget.ImageView; 9 10 import java.util.List; 11 12 /** 13 * RecyclerView.Adapter<MyViewHolder>尖括号里面的表示数据的类型 14 * RecyclerView有自己的Viewholder但是我们需要创建自己的viewholder去实现它 15 * Created by Zyh on 2016/9/19. 16 */ 17 public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> implements View.OnClickListener{ 18 Context content; 19 List<Dates> mDates; 20 LayoutInflater inflater; 21 22 public MyAdapter(Context content, List<Dates> mDates) { 23 this.content = content; 24 this.mDates = mDates; 25 this.inflater=LayoutInflater.from(content); 26 } 27 @Override 28 public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 29 View view=inflater.inflate(R.layout.item_main,null); 30 MyViewHolder viewHolder=new MyViewHolder(view); 31 return viewHolder; 32 } 33 @Override 34 public void onBindViewHolder(MyViewHolder holder, int position) { 35 holder.iT.setImageResource(mDates.get(position).mImageId); 36 holder.iT.setTag(position); 37 } 38 39 //设置数量 40 @Override 41 public int getItemCount() { 42 return mDates.size(); 43 } 44 45 OnRecyclerViewItemClickListener mListener; 46 47 48 // 定义一个接口里面有一个抽象的方法,重点是里面的参数,View要与点击事件的view相对应 49 protected interface OnRecyclerViewItemClickListener{ 50 public abstract void OnItem(View view,int position); 51 } 52 /** 定义一个方法,里面的参数是接口类型的对象,从而在创建接口对象的时候去实现接口的抽象方法, 53 抽象方法内的参数与系统点击事件的方法一致**/ 54 public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener mListener){ 55 this.mListener=mListener; 56 57 } 58 @Override 59 public void onClick(View view) { 60 61 if (mListener!=null){ 62 mListener.OnItem(view, (Integer) view.getTag()); 63 64 65 } 66 67 } 68 69 } 70 71 class MyViewHolder extends RecyclerView.ViewHolder { 72 ImageView iT; 73 public MyViewHolder(View itemView) { 74 super(itemView); 75 iT= (ImageView) itemView.findViewById(R.id.item_image); 76 } 77 }