欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android RecyclerView使用

程序员文章站 2022-05-14 19:37:21
...

        本文参照 《第一行代码 Android 第二版》进行整理,同时添加了一些书中该章节没涉及的内容。

一、RecyclerView 功能介绍

    RecyclerView可以说是一个增强版的ListView,它不仅可以实现ListView同样的效果,还优化了很多ListView 的不足之处。

比如:1.实现横向滑动     2. 实现GridView的效果    3. 实现瀑布流效果

    先贴几张效果图:

横向滑动:

Android RecyclerView使用

类似GridView效果:

Android RecyclerView使用

瀑布流效果:

Android RecyclerView使用


二、使用方法:

1. 添加依赖库

RecyclerView控件在support库中,因此,使用时,需现在build.gradle中添加相映的依赖库

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
2. 在activity_main.xml中使用RecyclerView控件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>
3.写每一项的布局
fruit_item.xml。使用过ListView的同学应该都知道,ListView也需要一个每一项的布局。其实和ListView还是挺相似的
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/apple_pic"
        android:id="@+id/fruit_image"/>

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="@string/app_name"
        android:layout_marginLeft="10dp"/>

</LinearLayout>

4. 为RecyclerView写一个适配器

使用过ListView的同学应该都知道,ListView需要一个适配器。RecyclerView也一样。

我们新建一个FruitAdapter类,继承RecyclerView.Adapter,并将其泛型指定为 FruitAdapter.ViewHolder。其中ViewHolder为FruitAdapter的内部类。

先给出适配器中用到的Fruit实体类,共两条属性,一条为水果名称。水果的图片放在drawable文件夹中,另一条属性为图片的id。

package com.czlt.test.recyclerviewtest.bean;

public class FruitBean {
    private String fruitName;
    private int fruitImageId;

    public String getFruitName() {
        return fruitName;
    }

    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }

    public int getFruitImageId() {
        return fruitImageId;
    }

    public void setFruitImageId(int fruitImageId) {
        this.fruitImageId = fruitImageId;
    }

    public FruitBean(String fruitName, int fruitImageId) {
        this.fruitName = fruitName;
        this.fruitImageId = fruitImageId;
    }
}

下面是重点:Adapter的代码

package com.czlt.test.recyclerviewtest.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.czlt.test.recyclerviewtest.bean.FruitBean;
import com.czlt.test.recyclerviewtest.R;

import java.util.List;

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder>{

    List<FruitBean> fruitList;

    /**
     * 构造方法
     * @param fruitList 数据源
     */
    public FruitAdapter(List<FruitBean> fruitList) {
        this.fruitList = fruitList;
    }

    /**
     * 创建ViewHolder
     * @param parent
     * @param viewType
     * @return
     */
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Log.i("test","onCreateViewHolder");
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
        final ViewHolder viewHolder = new ViewHolder(view);


        return viewHolder;
    }

    /**
     * 绑定ViewHolder,每加载一项都会调用一次
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Log.i("test","onBindViewHolder");
        FruitBean fruitBean = fruitList.get(position);
        holder.fruitImage.setImageResource(fruitBean.getFruitImageId());
        holder.fruitName.setText(fruitBean.getFruitName());

    }

    /**
     * 获取项数量
     * @return
     */
    @Override
    public int getItemCount() {
        return fruitList.size();
    }

    /**
     * RecyclerView的持有者类
     */
    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder(View view){
            super(view);
            fruitImage = view.findViewById(R.id.fruit_image);
            fruitName = view.findViewById(R.id.fruit_name);

        }

    }

}

其实上面代码逻辑还是比较清晰的,

        1. 创建ViewHolder类,与ListView的BaseAdapter区别在于需继承RecyclerView.ViewHolder。

    2. 重写 onCreateViewHolder,onBindViewHolder,getItemCount 三个方法。onCreateViewHolder用于创建ViewHolder实例,onBindViewHolder用于对每一项数据进行赋值,getItemCount用于告诉RecyclerView一共有多少子项。


附上一张日志的图片,从图片上日志来看,目测加载该控件时,每显示一项,就调用一次onCreateViewHolder方法和一次onBindViewHolder方法,后期滑动时候加载新的项只调用onBindViewHolder方法。

Android RecyclerView使用

5. 在MainActivity中使用RecyclerView
package com.czlt.test.recyclerviewtest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.czlt.test.recyclerviewtest.adapter.FruitAdapter;
import com.czlt.test.recyclerviewtest.bean.FruitBean;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
//    FruitBean f;
    private List<FruitBean> fruitList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler_view);
        initFruits();

        //设置适配器
        recyclerView.setAdapter(new FruitAdapter(fruitList));

        //构造 LinearLayputManager,并设置方向。LinearLayputManager效果类似ListView。
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        
        //设置滑动方向:纵向
//      layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //添加Android自带的分割线
//      recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

        //设置滑动方向:横向
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        //添加Android自带的分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL));
        recyclerView.setLayoutManager(layoutManager);
        

    }

    /**
     * 初始化数据
     */
    private void initFruits() {
        fruitList = new ArrayList<FruitBean>(24);
        for(int i=0;i<3;i++){
            fruitList.add(new FruitBean("Apple",R.drawable.apple_pic));
            fruitList.add(new FruitBean("Orange",R.drawable.orange_pic));
            fruitList.add(new FruitBean("Grape",R.drawable.grape_pic));
            fruitList.add(new FruitBean("Cherry",R.drawable.cherry_pic));
            fruitList.add(new FruitBean("Mango",R.drawable.mango_pic));
            fruitList.add(new FruitBean("Pear",R.drawable.pear_pic));
            fruitList.add(new FruitBean("Pineapple",R.drawable.pineapple_pic));
            fruitList.add(new FruitBean("Watermelon",R.drawable.watermelon_pic));
        }

    }
}

MainActivity中的逻辑也是比较清晰的,findViewById绑定控件,设置Adapter这两个步骤和ListView一样,多出的构造与设置LayoutManager的地方,也就是RecyclerView比ListView强大的地方。其中LinearLayoutManager就是类似ListView的效果,通过设置LinearLayoutManager的方向,即可实现横向滑动与纵向滑动。

上面代码最终的效果图:

Android RecyclerView使用

5. 设置每一项的点击事件

修改FruitAdapter 的onCreateViewHolder方法

    /**
     * 创建ViewHolder
     * @param parent
     * @param viewType
     * @return
     */
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Log.i("test","onCreateViewHolder");
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
        final ViewHolder viewHolder = new ViewHolder(view);

        /**
         * 设置点击监听事件
         */
        viewHolder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = viewHolder.getAdapterPosition();
                FruitBean fruitBean = fruitList.get(position);
                Toast.makeText(v.getContext(),"点击了"+fruitBean.getFruitName(),Toast.LENGTH_SHORT).show();
            }
        });

        return viewHolder;
    }

效果图:点击水果图片后,Toast显示对应水果名字。代码就不多做说明了。

Android RecyclerView使用

6. 实现类似GridView效果与瀑布流效果。

6.1 先看瀑布流效果:

为了更好的适应界面,我们简单修改一下每一项的布局 fruit_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_margin="5dp"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/apple_pic"
        android:id="@+id/fruit_image"/>

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:layout_marginLeft="10dp"/>

</LinearLayout>
为了实现瀑布流,最好要每一项的高度不相同。因此,初始化数据源时,我们也做一点修改新写一个GridActivity
package com.czlt.test.recyclerviewtest;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import com.czlt.test.recyclerviewtest.adapter.FruitAdapter;
import com.czlt.test.recyclerviewtest.bean.FruitBean;

import java.util.ArrayList;
import java.util.List;

public class GridActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    private List<FruitBean> fruitList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler_view);
        initFruits();
        recyclerView.setAdapter(new FruitAdapter(fruitList));

//        GridLayoutManager manager = new GridLayoutManager(this,4);
        //瀑布流布局,列数为4列,滑动方向为竖直方向
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);



        //添加系统自带的分隔线
//        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

        //添加系统自带的分隔线
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL));
    }




    /**
     * 初始化数据
     */
    private void initFruits() {
        fruitList = new ArrayList<FruitBean>(40);
        for(int i=0;i<5;i++){
            fruitList.add(new FruitBean("Appleasdadadadadadaqweqwasdswqsd",R.drawable.apple_pic));
            fruitList.add(new FruitBean("Orangefasfedddddddfewsdcqdsaq",R.drawable.orange_pic));
            fruitList.add(new FruitBean("Grapesdfasdxcadfxdfedascfdedwgre",R.drawable.grape_pic));
            fruitList.add(new FruitBean("Cherrywedfwerfdswerfdswerfdswerfswer",R.drawable.cherry_pic));
            fruitList.add(new FruitBean("Mangoergffrgedtgdfdr",R.drawable.mango_pic));
            fruitList.add(new FruitBean("Pearerfgredfgerd",R.drawable.pear_pic));
            fruitList.add(new FruitBean("Pineapplewsrdswerdsfgfrtedggerdre",R.drawable.pineapple_pic));
            fruitList.add(new FruitBean("Watermelon",R.drawable.watermelon_pic));
            fruitList.add(new FruitBean("Watermelossdn",R.drawable.strawberry_pic));
        }

    }
}

效果图:

Android RecyclerView使用

6.2 实现GridView效果与自定义分隔线

先在drawable目录下写一个自定义分隔线costom_divider.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:centerColor="#ff00ff00"
    android:endColor="#ff0000ff"
    android:startColor="#ffff0000"
    android:type="linear" />
    <size android:height="2dp" />

</shape>

实际上就是一个渐变颜色的线条

然后修改GridActivity

package com.czlt.test.recyclerviewtest;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.czlt.test.recyclerviewtest.adapter.FruitAdapter;
import com.czlt.test.recyclerviewtest.bean.FruitBean;

import java.util.ArrayList;
import java.util.List;

public class GridActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    private List<FruitBean> fruitList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler_view);
        initFruits();
        recyclerView.setAdapter(new FruitAdapter(fruitList));

        //网格布局,4列
        GridLayoutManager manager = new GridLayoutManager(this,4);
        //瀑布流布局,列数为4列,滑动方向为竖直方向
//        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);


        //添加自定义分隔线
        //构造 DividerItemDecoration 对象,并设置方向
        DividerItemDecoration divider = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        //设置分隔线的 drawable 资源
        Resources resources = this.getResources();
        divider.setDrawable(resources.getDrawable(R.drawable.divider));
        //添加至 RecyclerView
        recyclerView.addItemDecoration(divider);


        //添加系统自带的分隔线
//        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

        //添加系统自带的分隔线
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL));
    }




    /**
     * 初始化数据
     */
    private void initFruits() {
        fruitList = new ArrayList<FruitBean>(40);
        for(int i=0;i<5;i++){
            fruitList.add(new FruitBean("Appleasdadadadadadaqweqwasdswqsd",R.drawable.apple_pic));
            fruitList.add(new FruitBean("Orangefasfedddddddfewsdcqdsaq",R.drawable.orange_pic));
            fruitList.add(new FruitBean("Grapesdfasdxcadfxdfedascfdedwgre",R.drawable.grape_pic));
            fruitList.add(new FruitBean("Cherrywedfwerfdswerfdswerfdswerfswer",R.drawable.cherry_pic));
            fruitList.add(new FruitBean("Mangoergffrgedtgdfdr",R.drawable.mango_pic));
            fruitList.add(new FruitBean("Pearerfgredfgerd",R.drawable.pear_pic));
            fruitList.add(new FruitBean("Pineapplewsrdswerdsfgfrtedggerdre",R.drawable.pineapple_pic));
            fruitList.add(new FruitBean("Watermelon",R.drawable.watermelon_pic));
            fruitList.add(new FruitBean("Watermelossdn",R.drawable.strawberry_pic));
        }

    }
}

效果图:

Android RecyclerView使用

源代码地址:

https://download.csdn.net/download/qq_34763699/10393645

https://pan.baidu.com/s/1hvSEJi6ji76zznyQhS34rA

相关标签: RecyclerView