目录
ListView只能实现数据纵向滚动的效果,如果想实现横向滚动的话,ListView是做不到的。为此,Android提供了一个更强大的滚动控件——RecyclerView。它可以说是一个增强版的ListView。
RecyclerView提供了三种布局方式:LinearLayoutManager(线性布局)、GridLayoutManager(网格布局)和StaggeredGridLayoutManager(瀑布流布局)。
一、RecyclerView的基本用法(LinearLayoutManager)
1、添加依赖
dependencies {
......
'androidx.recyclerview:recyclerview:1.1.0'
}
2、在布局中添加RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
3、编写item布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/image_item"
android:layout_width="wrap_content"
android:layout_height="50dp" />
<TextView
android:id="@+id/text_iem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
4、定义适配器
这是使用RecyclerView最关键的一步。需要关注以下2点:
1)ViewHolder
RecyclerView之所以能快速展示大量数据,ViewHolder可以说是功不可没。
ViewHolder要继承自RecyclerView.ViewHolder。ViewHolder的构造函数中传入了一个View参数,可以初始化需要展示的控件。
2)必须重写的3个方法
- onCreateViewHolder(ViewGroup parent, int viewType)
用于创建ViewHolder的实例 - onBindViewHolder(ViewHolder holder, int position)<