前言
完整项目 托管在 github 上,直达电梯:豆瓣电影客户端 github
也可以先看前两篇文章:
Android 从零开始-豆瓣电影客户端
Android 从零开始-网络缓存实现与分析
一、基础
RecyclerView 是个支持库,存在 `com.android.support` 之中,集成方式
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:recyclerview-v7:24.1.1'
目前使用的是 24.1.1 版本。可以根据自己的情况使用不同的版本,建议升级到最新版,因为有些 bug 也在不断修复中,如果你说没有 bug, 或许是没有碰到呢。
在 RecyclerView 中存在 三种 布局管理模式 分别是:LinearLayoutManager
、GridLayoutManager
、StaggeredGridLayoutManager
豆瓣客户端中使用了 两种 布局管理模式 分别是 LiearLayoutManager
和 GridLayoutManager
,
LinearLayoutManager
定义
顾名思义局势 线性布局模式,这个是我们用的最多的方式,呈现效果就是顺序排列而下的方式使用
- xml 布局直接使用:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:orientation="vertical"
android:padding="4dp"
android:scrollbarStyle="insideOverlay"
android:scrollbars="vertical"
app:layoutManager="android.support.v7.widget.LinearLayoutManager"
/>
- Java 代码中定义
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
GridLayoutManager
- 定义
网格布局,一排可以显示1格、或者更多格。
使用
- xml 布局直接使用:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:orientation="vertical"
android:padding="4dp"
android:scrollbarStyle="insideOverlay"
android:scrollbars="vertical"
app:layoutManager="android.support.v7.widget.GridLayoutManager"
app:spanCount="3" />
app:layoutManager
定义布局方式,app:spanCount="3"
列数。
需要在 xml 布局中加入 xmlns:app="http://schemas.android.com/apk/res-auto"
- Java 代码中定义
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getContext(), 3);
mRecyclerView.setLayoutManager(mGridLayoutManager);
StaggeredGridLayoutManager
- 定义
流线型布局方式,就是通常说的瀑布流的效果。
使用
- java 代码中定义
// 交错网格布局管理器
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
// 设置布局管理器
recyclerView.setLayoutManager(staggeredGridLayoutManager);
其中设置 StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL)
的 数字 2 指代的是列数,LinearLayoutManager.VERTICAL 和方向。
二、进阶
- 下图不规则布局效果是怎么实现出来的呢?
是这个方法的使用 SpanSizeLookup
:
mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (position % 4) {
case 0:
return 3;
default:
return 1;
}
}
});
其中 position % 4
每4条数据一个循环,return 3;
表示此条数据占 3 列,即一行显示一条数据。
- 上拉加载更多 效果怎么实现呢?
限于篇幅,下篇文章详细介绍。