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