RecyclerView入门

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) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值