0、前言
如今RecyclerView已经逐渐取代ListView,成为Android开发中最常用的控件之一,它在用法上也与ListView类似,为了方便使用,也可以参照ListView封装出一个可复用适配器。本文主要根据鸿洋大神的文章编写,并结合了自己对于RecyclerView基本用法的一些总结。
1、RecyclerView的基本用法
首先回顾下RecyclerView的基本用法,新建一个RecyclerViewDemo项目,打开app/build.gradle文件,在dependencies闭包中添加相应的依赖库,如下所示:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
}
修改activity_main.xml中的代码,如下所示:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
然后在layout目录下为列表项新建一个自定义的布局文件recyclerview_item.xml,在这个布局中,定义了一个TextView用于显示文本,一个ImageView用于显示图片,代码如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:orientation="horizontal">
<TextView
android:id="@+id/text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"