关于RecyclerView的基础知识

1.基础知识:
a.更改item显示的风格:LayoutManager
b.设置item如何分隔(定制分割线样式):ItemDecoration
c.为item添加增加与删除动画:itemAnimator
d.RecyclerView强制用户实现viewHolder类,所以要重写viewHolder类

2.关于使用
a.先引入依赖库


Paste_Image.png

b.在布局文件中添加RecyclerView


c.重写Adapter类,实现必须的方法

public class SimpleAdapter extends RecyclerView.Adapter{
public int getItemCount() {
return mDatas.size();
}
//将ViewHolder的组件与数据绑定
public void onBindViewHolder(final MyViewHolder holder, final int position) {
    holder.tv.setText(mDatas.get(position));
}
//初始化ViewHolder
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {    //将每个item布局动态加载进来(因为初始化MyViewHolder要用到)
  View itemView =mInflater.inflate(R.layout.item_simple_textview,parent,false);
  MyViewHolder myViewHolder = new MyViewHolder(itemView);    
  return myViewHolder;
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {    //将每个item布局动态加载进来(因为初始化MyViewHolder要用到)  
  View itemView = mInflater.inflate(R.layout.item_simple_textview,parent,false);        MyViewHolder myViewHolder = new MyViewHolder(itemView);   
 return myViewHolder;}
}

d.利用LayoutManager设置item显示的风格

//将RecyclerView设置成垂直ListView的样式:(更改orientation可变水平)
mRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
// 将RecyclerView设置成垂直GridView的样式,其中3为3列:
mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));
//将RecyclerView设置成水平GridView的样式,其中5为5行:
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5,StaggeredGridLayoutManager.HORIZONTAL));

e.利用ItemDecoration设置divider,需要继承ItemDecoration实现子类
关于调用:

mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST));

f.利用ItemAnimator设置动画。
关于调用:DefaultItemAnimator为系统提供的默认类

mRecyclerView.setItemAnimator(new DefaultItemAnimator());

g.在Adapter写删除和添加item的方法:

public void addData(int pos){
        mDatas.add(pos,"Insert one");
     //不能写notifyDataSetChanged(),写这个没有动画效果
        notifyItemInserted(pos);    
}
    public void deleteData(int pos){
        mDatas.remove(pos);
        notifyItemRemoved(pos);    
}

h.因为RecyclerView没有向外提供点击事件,所以要暴露接口向外提供点击事件:

public interface OnItemClickListener{
    void onItemLongClick(View view,int pos);
    void onItemClick(View view,int pos);
}
private OnItemClickListener mListener;
public void setOnItemClickListener(OnItemClickListener listener){
    this.mListener = listener;
}

onBindViewHolder()方法中添加如下方法实现接口回调

if(mListener!=null) {
    holder.itemView.setOnClickListener(new View.OnClickListener() {        @Override
        public void onClick(View v) {            mListener.onItemClick(v,holder.getLayoutPosition());
        }
    });
    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            mListener.onItemLongClick(v,holder.getLayoutPosition());            
            return true;
        }
    });
}

你可能感兴趣的:(关于RecyclerView的基础知识)