安卓控件RecyclerVieW


  RecyclerView是官方在5.0之后新添加的控件,推出用来替代ListView和GridView的列表控件。为了保证RecyclerView在所有Android系统版本上都能使用。Google将RecyclerView控件定义在了AndroidX中,只需要在项目的build.gradle中添加RecyclerView库的依赖,就能保证在所有Android系统版本上都可以使用RecyclerView控件了。RecyclerView会回收视图重复利用。当列表滚动展示区域之外(宽度或高度超出父容器)时,RecyclerView不会销毁视图,而是将视图置于列表滑动方向准备显示的那端。这种渲染方式可以显著提高性能。

导入依赖

  file→Project Structure…→Dependencies→ app→ + → Library Dependency。
在这里插入图片描述

  输入androidx.recyclerview,然后点击Search。

在这里插入图片描述

简单使用

  修改activity_main.xml中的代码。在布局中加入RecyclerView控件也是非常简单的,先为RecyclerView指定一个id,然后将宽度和高度都设置为match_parent,这样RecyclerView就占满了整个布局的空间。需要注意的是,由于RecyclerView并不是内置在系统SDK当中的,所以需要把完整的包路径写出来。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

  自定义布局fruit_item.xml。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp">
    <ImageView
        android:id="@+id/fruitImage"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"/>
    <TextView
        android:id="@+id/fruitName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp" />
</LinearLayout>

  编写Fruit类。

public class Fruit {
   
   
    private String name;
    private int imageId;

    public Fruit(String name,int imageId){
   
   
        this.name = name;
        this.imageId = imageId
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姜君竹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值