RecyclerView 可以让您轻松高效地显示大量列表数据。您提供数据并定义每个列表项的外观,而 RecyclerView 库会根据需要动态创建元素。
当列表项滚动出屏幕时,RecyclerView不会销毁其视图,而是会被回收,对屏幕上滚动的新列表项重用该视图。RecyclerView可以让您轻松高效地显示大量数据。 可提升性能和应用的响应能力,并降低功耗。
一、简单使用
1. fragment_module.xml
在页面中添加一个RecyclerView布局,并将RecyclerView布局设置为线性布局、垂直分布、从上到下排列。
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_module"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
app:layoutManager="LinearLayoutManager"
app:reverseLayout="false" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
2. item_module.xml
定义列表项的外观
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="data"
type="com.example.myapplication.bean.ModuleBean" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="140dp">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:background="@drawable/shape_module_bg" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text='@{data.name, default="一个模块名"}' />
<TextView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="top|end"
android:layout_marginEnd="8dp"
android:background="@drawable/shape_circle_tip"
android:gravity="center"
android:text='@{data.num+"", default=99}'
android:textColor="@color/white" />
</FrameLayout>
</layout>
3. ModuleRecyclerViewHolder.java
定义一个 ViewHolder
,用于存储列表项的一个布局实例。
我们可以在 ViewHolder
自由编写操作布局实例的函数,用于将数据渲染到布局上,例如 setStatus
函数。
public class ModuleRecyclerViewHolder extends RecyclerView.ViewHolder {
private final ItemModuleBinding binding;
public ModuleRecyclerViewHolder(@NonNull ItemModuleBinding binding)