本文目录
一、概述
RecyclerView 是在 Android5.0 之后,Google 推出的一个新控件,是作为 ListView、GridView 的替代者出现的。它具有比上述两者更高的灵活性,在功能上也更加强大。Google 官方对它的定义是:
A flexible view for providing a limited window into a large data set.
向一个有限的窗口(window)提供大量数据集的灵活视图(view)。
先来看看 RecyclerView 能实现哪些效果:
由于 RecylerView 定义在了 support 库中,如果我们想要使用 RecyclerView 控件,需要向项目中的 build.gradle添加代码 implementation ‘com.android.support:recyclerview-v7:27.1.1’ ,如下所示:
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:recyclerview-v7:27.1.1'
}
添加完之后一定要记得点一下右上角的 Sync Now 进行同步,否则可能会出现错误。
二、列表视图的处理
1. item 的布局文件
首先,在 activity_main 中添加 RecyclerView 控件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
其次,在 layout 文件夹下新建一个 Layout Resource file,命名为 item_recycler_view,它是 RecyclerView 中 item(即子项)的布局文件,我们需要的 item 布局为图片(ImageView)和文字(TextView)的组合,所以代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_item"
android:layout_width="80dp"
android:layout_height="80dp" />
<TextView
android:id="@+id/tv_item"