【Android基础】RecyclerView

本文详细介绍了Android中的RecyclerView,从基本用法到高级应用,包括LinearLayoutManager的配置,添加分割线,实现横向滚动,使用GridLayoutManager和StaggeredGridLayoutManager,以及如何处理RecyclerView的点击事件。关键步骤如定义ViewHolder,初始化RecyclerView,自定义分割线等都有详细讲解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值