RecyclerView基本用法
初识RecyclerView
RecyclerView | Android Developers
A flexible view for providing a limited window into a large data set.
根据数据集显示元素的滚动列表
RecyclerView的特点
- 优化了ListView
- ViewHolder----把view封装起来
- layoutmanager 布局管理器 控制Item的布局方式
- ItemDecoration 设置Item的间隔样式
- ItemAnimato 控制Item增删的动画
使用 RecyclerView 创建列表
添加依赖库
打开app包下的build.gradle 找到 dependencies{}
插入以下代码
implementation "androidx.recyclerview:recyclerview:1.1.0"
接着你会发现右上角出现了Sync Now字眼,我们点击他来重新Sync
依赖库的各个版本可以在官网里找到https://developer.android.com/jetpack/androidx/releases/recyclerview#declaring_dependencies
将RecyclerView添加到布局中
打开我们的activity_main.xml布局文件,将RecyclerView添加到布局中,给他命名为my_re_view
<?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">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/my_re_view"
android:scrollbars="vertical"/>
</LinearLayout>
定义一个名为TextItem的java类
新建java文件,用我们之前所学的java类与构造函数的知识定义一个实体类,定义两个变量,一个是int类型的ImageId,一个是String类型的textId
public class TextItem {
private int ImageId;
private String textId;
public TextItem(int imageId, String textId) {
ImageId = imageId;
this.textId = textId;
}
public int getImageId() {
return ImageId;
}
public void setImageId(int imageId