DataList是外部传入的子项数据列表
//定义适配器类
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
private Context context;
private List<People> DataList;
//编写导入数据的通用构造方法
MyAdapter(Context context, List<People> DataList){
this.context=context;
this.DataList=new ArrayList<>(DataList);
}
/*
以下三个方法和一个类是必须要重写的方法
*/
//ViewHolder(子项视图保存类):将当前Item视图都实例化保存起来,避免反复调用findViewById方法,浪费资源
//此处不能使用Butterknife
class MyViewHolder extends RecyclerView.ViewHolder{
TextView itemText;
ImageView itemImage;
public MyViewHolder(View itemView) {
super( itemView );
itemText=itemView.findViewById( R.id.itemText );
itemImage=itemView.findViewById( R.id.itemImage );
}
}
//创建ViewHolder实例并返回,加载item 的布局
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.itemlayout,parent,false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
//对RecyclerView子项数据进行赋值,将子项数据与ViewHolder里的控件进行绑定(设置)
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.itemText.setText( DataList.get( position ).getData() );
holder.itemImage.setImageResource( DataList.get( position ).getImageId() );
//把图片进行按比例缩放
holder.itemImage.setScaleType( ImageView.ScaleType.FIT_CENTER );
//自定义点击事件(直接在Adapter类重写点击事件)
/*holder.itemView.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText( context, ""+position,Toast.LENGTH_SHORT).show();
}
} );*/
//自定义点击事件(点击后触发的是:holder.itemView.setOnClickListener方法,
//然后调用自定义监听时间接口的onItemClick(position)方法,具体执行代码由外部实现)
if (myItemClickListener != null) {
holder.itemView.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
myItemClickListener.onItemClick(position );
}
} );
}
}
//返回子项(Item)个数
@Override
public int getItemCount() {
return DataList.size();
}
//自定义监听事件接口ItemClickListener ,和在Adapter类里的引用myItemClickListener
private ItemClickListener myItemClickListener;
public interface ItemClickListener{
void onItemClick( int position);//点击监听事件,在外部实现
}
//让外部能够使用setItemClickListener给ItemClickListener内部引用赋值
public void setItemClickListener(ItemClickListener myItemClickListener) {
this.myItemClickListener = myItemClickListener;
}
//让外部能添加和删除Item的方法
public void addItem(int position,People people){
DataList.add( position,people );
//增添动作刷新适配器
notifyItemInserted( position );
}
public void removeItem(int position){
DataList.remove( position );
//删除动作刷新适配器
notifyItemRemoved( position );
}
}