RecyclerView使用总结



1、RecyclerView用途:实现ListView,GridView,瀑布流


2、RecyclerView用法:

rv.setLayoutManager(new LinearLayoutManager(getActivity()));//设置布局
        rv.setAdapter(adapter);//设置适配器
        rv.setItemAnimator(new DefaultItemAnimator());//设置动画
        rv.addItemDecoration(new DividerGridItemDecoration(this));//设置分割线


 
   
  
3、三种布局:
LinearLayoutManager :线性布局
GridLayoutManager :网格布局
 
  
StaggeredGridLayoutManager:瀑布流布局





4、自定义适配器






a、自定义ViewHolder
b、重写onCreateViewHolder方法,返回自定义viewholder
c、重写onBindViewHolder方法,绑定viewholder







package com.recyclerview.example.annieliu.recyclerviewtest;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by annieliu on 2016/2/5.
 */
public class MyRecyclerAdapter extends RecyclerView.Adapter{

    private List data;
    private Context ctx;

    public MyRecyclerAdapter(List data, Context ctx) {
        this.data = data;
        this.ctx = ctx;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(ctx).inflate(R.layout.list_item,parent,false));
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        final String value=data.get(position);
        holder.tv.setText(value);

        holder.tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(value);
            }
        });

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{
        TextView tv;
        public MyViewHolder(View itemView) {
            super(itemView);
            tv=(TextView)itemView.findViewById(R.id.tv_list_item_num);
        }
    } 

}






5、动画

提供一种自定义动画:DefaultItemAnimator;其他自定义动画:https://github.com/gabrielemariotti/RecyclerViewItemAnimators






6、分割线:没有提供默认分割线;可继承RecyclerView.ItemDecoration 实现自定义分割线;参考资料:http://blog.csdn.net/lmj623565791/article/details/45059587
 
  
7、其他:item的点击事件可以使用EventBus实现,优点:解耦合;具体参见另一篇博文。
 
  
参考资料:http://blog.csdn.net/lmj623565791/article/details/45059587




 
 

你可能感兴趣的:(Android)