RecyclerView<第四篇>:布局管理器

RecyclerView常用的布局管理器有三种,分别是LayoutManager、GridLayoutManager、StaggeredGridLayoutManager。

Recyclerview必须设置布局管理器(即LayoutManager),如果没有设置,Recyclerview将不会展示数据。

  • LayoutManager(线性布局)

LayoutManager让Recyclerview的数据线性显示,线性显示又分为两种:纵向和横向

纵向:(默认就是纵向,可以不用特意设置方向)

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(linearLayoutManager);
61.gif

横向:(如果需要横向显示的话,需要设置方向)

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
    linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    mRecyclerView.setLayoutManager(linearLayoutManager);
60.gif

Recyclerview默认是纵向显示,但是如果想要横向显示该怎么做呢?

  • GridLayoutManager(网格布局)

GridLayoutManager是九宫格布局,它同样有两种方向:纵向和横向。

纵向:

    GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
    gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(gridLayoutManager);
62.gif

横向:

    GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
    gridLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
    mRecyclerView.setLayoutManager(gridLayoutManager);
63.gif
  • StaggeredGridLayoutManager(瀑布流布局)

所谓瀑布流布局就是可以让Item交错的的布局,代码如下:

    final StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);//不设置的话,图片闪烁错位,有可能有整列错位的情况。
    mRecyclerView.setLayoutManager(staggeredGridLayoutManager);
    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            staggeredGridLayoutManager.invalidateSpanAssignments();//这行主要解决了当加载更多数据时,底部需要重绘,否则布局可能衔接不上。
        }
    });
64.gif

有些时候LinearLayoutManager、GridLayoutManager和StaggeredGridLayoutManager都不能满足我们的需求,所以需要自定义LayoutManager

[本章完...]

你可能感兴趣的:(RecyclerView<第四篇>:布局管理器)