RecycleView的分页加载和多布局

引包:
compile 'com.android.support:recyclerview-v7:24.2.1'
compile 'com.jakewharton:butterknife:8.4.0'
compile 'com.android.support:cardview-v7:24.2.1'
代码:
public class Album {
    String name;
    String artist;
    int position;
    int price;
    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Album(String name, String artist) {
        this.name = name;
        this.artist = artist;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    @Override
    public String toString() {
        return "Album{" +
                "name='" + name + '\'' +
                ", artist='" + artist + '\'' +
                '}';
    }

}
*********************************************************************************
public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}
*********************************************************************************
public class ListActivity extends AppCompatActivity {

    private static final String TAG = "test";
    private ListView lv;
    private List data = new ArrayList<>();
    private MyListAdapter adapter;
    int currentScrollState;
    private View footerView;
    int lastVisibleItem;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        lv = ((ListView) findViewById(R.id.lv));
        footerView = LayoutInflater.from(this).inflate(R.layout.footer,lv,false);

        initData();

        adapter = new MyListAdapter(this,data);
        lv.setAdapter(adapter);

        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if(lastVisibleItem == data.size()-1 && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE){
                    lv.addFooterView(footerView);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < 10; i++) {
                                data.add(new Album("MoreOne-"+i,"MoreArtist-"+i));
                            }
                            adapter.notifyDataSetChanged();
                            lv.removeFooterView(footerView);
                        }
                    }, 3000);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lastVisibleItem = firstVisibleItem + visibleItemCount - 1;
            }
        });
    }


    private void initData() {
        for (int i = 0; i < 20; i++) {
            Album album = new Album("专辑名称-" + i, "艺术家-" + i);
            album.setPosition(i);
            album.setPrice(200 + new Random().nextInt(200));
            data.add(album);
        }
    }
}
*********************************************************************************
public class MainActivity extends AppCompatActivity implements MyAdapter.OnItemClickListener,MyAdapter.LoadMoreListener{

    private static final String TAG = "test";
    private RecyclerView rv;
    private List data = new ArrayList<>();

    private LinearLayoutManager linearLayoutManager;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private RecyclerView.LayoutManager currentLayoutManager = null;
    private MyAdapter linearAdapter;
    private MyAdapter gridAdapter;

    private GridLayoutManager gridLayoutManager;
    private MyAdapter currentAdapter;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv = (RecyclerView) findViewById(R.id.rv);

        initData();
        initAdapterAndLayout();
        initAnimAndDecoration();

    }

    private void initAnimAndDecoration() {
        rv.setItemAnimator(new DefaultItemAnimator());
        rv.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST));
        rv.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL_LIST));
    }

    private void initAdapterAndLayout() {
        linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        gridLayoutManager = new GridLayoutManager(this,2, LinearLayoutManager.VERTICAL,false);
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);//流式布局管理器

        linearAdapter = new MyAdapter(this,data,MyAdapter.LINEAR_LAYOUT_MANAGER);
        gridAdapter = new MyAdapter(this,data,MyAdapter.GRID_LAYOUT_MANAGER);
        linearAdapter.setOnItemClickListener(this);
        gridAdapter.setOnItemClickListener(this);
        linearAdapter.setLoadMoreListener(this);
        gridAdapter.setLoadMoreListener(this);

        useLinearLayout();
    }

    private void initData() {
        for (int i = 0; i < 20; i++) {
            Album album = new Album("专辑名称-" + i, "艺术家-" + i);
            album.setPosition(i);
            album.setPrice(200 + new Random().nextInt(200));
            data.add(album);
        }
    }

    public void switchLayout(View view) {
        if(currentLayoutManager == linearLayoutManager){
            useGridLayout();
        }else{
            useLinearLayout();
        }
    }

    private void useGridLayout() {
        rv.setLayoutManager(gridLayoutManager);
        rv.setAdapter(gridAdapter);
        currentLayoutManager = gridLayoutManager;
        currentAdapter = gridAdapter;
    }

    private void useLinearLayout() {
        rv.setLayoutManager(linearLayoutManager);
        rv.setAdapter(linearAdapter);
        currentLayoutManager = linearLayoutManager;
        currentAdapter = linearAdapter;
    }

    @Override
    public void onItemClick(int position) {
        Toast.makeText(MainActivity.this, "MainActivity:"+data.get(position).getName(), Toast.LENGTH_SHORT).show();
    }

    public void addItem(View view) {
        if(currentAdapter!=null){
            data.add(0,new Album("NewOne","NewArtist"));
//            currentAdapter.notifyDataSetChanged();
            currentAdapter.onNotifyItemInserted(0,rv);
        }
    }

    public void removeItem(View view) {
        if(currentAdapter!=null){
            data.remove(0);
//            currentAdapter.notifyDataSetChanged();
            currentAdapter.onNotifyItemRemoved(0,rv);
        }
    }

    @Override
    public void loadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    data.add(new Album("MoreOne-"+i,"MoreArtist-"+i));
                }
                currentAdapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this, "分页数据加载完成!", Toast.LENGTH_SHORT).show();
            }
        }, 3000);
    }

}
*********************************************************************************
public class MyAdapter extends RecyclerView.Adapter {

    public static final int LINEAR_LAYOUT_MANAGER = 0;
    public static final int GRID_LAYOUT_MANAGER = 1;

    private int layoutManager = LINEAR_LAYOUT_MANAGER;
    Context context;
    List albums;

    private View view;

    public MyAdapter(Context context, List albums, int layoutManager) {
        this.context = context;
        this.albums = albums;
        this.layoutManager = layoutManager;
    }

    public void setLayoutManager(int layoutManager) {
        this.layoutManager = layoutManager;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return albums.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == albums.size()) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 1) {
            view = LayoutInflater.from(context).inflate(R.layout.footer, parent, false);
            return new FooterHolder(view);
        }

        switch (layoutManager) {
            case LINEAR_LAYOUT_MANAGER:
                view = LayoutInflater.from(context).inflate(R.layout.item_rvadapter_linear, parent, false);
                break;
            case GRID_LAYOUT_MANAGER:
                view = LayoutInflater.from(context).inflate(R.layout.item_rvadapter_grid, parent, false);
                break;
        }

        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

        if(holder instanceof FooterHolder){
            if(loadMoreListener != null){
                loadMoreListener.loadMore();
            }
            return;
        }

        Holder _holder = (Holder) holder;
        Album album = albums.get(position);
        _holder.tvAlbumn.setText(album.getName());
        _holder.tvArtist.setText(album.getArtist());

        _holder.cvRoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(position);
                }
            }
        });
    }

    LoadMoreListener loadMoreListener;

    public void setLoadMoreListener(LoadMoreListener loadMoreListener) {
        this.loadMoreListener = loadMoreListener;
    }

    interface LoadMoreListener {
        void loadMore();
    }

    OnItemClickListener onItemClickListener;

    interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void onNotifyItemInserted(int positiion, RecyclerView rv) {
        notifyItemInserted(positiion);
        rv.scrollToPosition(0);
    }

    public void onNotifyItemRemoved(int positiion, RecyclerView rv) {
        notifyItemRemoved(positiion);
        rv.scrollToPosition(0);
    }

    static class Holder extends RecyclerView.ViewHolder {
        @BindView(R.id.tvAlbumn)
        TextView tvAlbumn;
        @BindView(R.id.tvArtist)
        TextView tvArtist;
        @BindView(R.id.tvInfo)
        TextView tvInfo;
        @BindView(R.id.llRoot)
        LinearLayout llRoot;
        @BindView(R.id.cvRoot)
        CardView cvRoot;

        Holder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    static class FooterHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.pb)
        ProgressBar pb;
        @BindView(R.id.tv)
        TextView tv;

        FooterHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}
*********************************************************************************
public class MyListAdapter extends BaseAdapter {

    private final LayoutInflater inflater;
    Context context;
    List data;

    public MyListAdapter(Context context, List data) {
        this.context = context;
        this.data = data;
        inflater = LayoutInflater.from(context);
    }

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

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_rvadapter_linear, parent, false);
            holder = new Holder(convertView);
            convertView.setTag(holder);
        }else {
            holder = ((Holder) convertView.getTag());
        }

        Album album = data.get(position);
        holder.tvAlbumn.setText(album.getName());
        holder.tvArtist.setText(album.getArtist());

        return convertView;
    }


    static class Holder {
        @BindView(R.id.tvAlbumn)
        TextView tvAlbumn;
        @BindView(R.id.tvArtist)
        TextView tvArtist;
        @BindView(R.id.tvInfo)
        TextView tvInfo;
        @BindView(R.id.llRoot)
        LinearLayout llRoot;
        @BindView(R.id.cvRoot)
        CardView cvRoot;

        Holder(View view) {
            ButterKnife.bind(this, view);
        }
    }

}

布局文件:
(activity_list)



    


*********************************************************************************
(activity_main)



    

    

        

运行结果:

RecycleView的分页加载和多布局_第1张图片

点击切换布局:

RecycleView的分页加载和多布局_第2张图片

加载更多:

RecycleView的分页加载和多布局_第3张图片

增加条目:

RecycleView的分页加载和多布局_第4张图片

增加条目:

RecycleView的分页加载和多布局_第5张图片

移除条目:
RecycleView的分页加载和多布局_第6张图片

你可能感兴趣的:(RecycleView的分页加载和多布局)