在使用RecyclerView时候,必须指定一个适配器Adapter和一个布局管理器LayoutManager。
recyclerView=(RecyclerView)findViewById(R.id.recyclerView);
LinearLayoutManagerlayoutManager=newLinearLayoutManager(this);
//设置布局管理器 recyclerView.setLayoutManager(layoutManager);
//设置为垂直布局,这也是默认的 layoutManager.setOrientation(OrientationHelper.VERTICAL);
//设置Adapter recyclerView.setAdapter(recycleAdapter);
//设置分隔线 recyclerView.addItemDecoration(newDividerGridItemDecoration(this));
//设置增加或删除条目的动画 recyclerView.setItemAnimator(newDefaultItemAnimator());
// ① 创建Adapter
public class NormalAdapter extends RecyclerView.Adapter<NormalAdapter.VH>{
//② 创建ViewHolder
public static class VH extendsRecyclerView.ViewHolder{
public final TextViewtitle;
public VH(Viewv) {super(v);
title=(TextView)v.findViewById(R.id.title);}}
private List<String> mDatas;
public NormalAdapter(List<String>data){this.mDatas=data;}
//③ 在Adapter中实现3个方法
@Override
public void onBindViewHolder(VHholder,intposition){holder.title.setText(mDatas.get(position));
holder.itemView.setOnClickListener(newView.OnClickListener(){
@Override
public void onClick(Viewv){//item 点击事件}});
}
@Override
public int getItemCount(){returnmDatas.size();}
@Override
public VH onCreateViewHolder(ViewGroupparent,intviewType){
//LayoutInflater.from指定写法
View v=LayoutInflater.from(parent.getContext()).inflate(R.layout.item_1,parent,false);
return newVH(v);}}