Android中RecyclerView配合SmartRefreshLayout实现下拉刷新以及优化(二)

上一篇为大家介绍了RecyclerView的简单使用,但是他还是缺失很多功能。今天这篇为优化他而来。有如下优化点:
  • 增加下拉刷新和上拉加载
  • 给RecyclerView配置一张没有数据时候的默认图片

说明:

一,使用的Androidstudio版本为3.1.3

二,基于RecyclerView配合BaseRecyclerViewAdapterHelper的简单使用(一)

三,SmartRefreshLayout号称是智能的下拉刷新框架。不会导致内部嵌套滑动控件的实效。github上有1万多个start。应用很广泛,接入简单。深受好评。

基于RecyclerView配合BaseRecyclerViewAdapterHelper的简单使用(一)的地址:https://www.jianshu.com/p/ce972355c71d
SmartRefreshLayout的github地址为:https://github.com/scwang90/SmartRefreshLayout

展示效果:

展示图.gif

现在正式开始

1,在build.gradle中增加下拉刷新SmartRefreshLayout的依赖

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.mumu.jsrecyclerview1"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

//1,增加jitpack支持
allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
        flatDir {
            dirs 'libs'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    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'

    //butterKnife
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

    //2,增加recycle和对应的适配器
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.30'

    //增加下拉刷新SmartRefreshLayout的依赖
    implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0-alpha-14'
    implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.1.0-alpha-14'//没有使用特殊Header,可以不加这行
}

2,修改RecyclerView对应的布局文件。将RecyclerView嵌套在SmartRefreshLayout中,然后分别在RecyclerView的上下增加ClassicsHeader和ClassicsFooter的头文件和脚文件。该头文件和脚文件的xml属于经典款式。官网上还有很多优秀的样式可以直接引用。然后给SmartRefreshLayout增加一个id便于在activity中使用。

  • app:srlEnablePreviewInEditMode="true" 表示可以预览头文件和脚文件
  • app:srlPrimaryColor="#00000000" 表示下拉刷新的背景色
  • app:srlAccentColor="@color/colorPrimary" 表示头文件和脚文件中文字的颜色
<?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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/srl_test"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srlAccentColor="#00000000"
        app:srlEnablePreviewInEditMode="true"
        app:srlPrimaryColor="#00000000">

        <com.scwang.smartrefresh.layout.header.ClassicsHeader
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srlAccentColor="@color/colorPrimary" />

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

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

        <com.scwang.smartrefresh.layout.footer.ClassicsFooter
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srlAccentColor="@color/colorPrimary" />

    </com.scwang.smartrefresh.layout.SmartRefreshLayout>
</LinearLayout>

3,增加一个没有数据时候的空布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F6F7F9"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/tv_empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="暂无数据"
        android:textColor="#999999"
        android:textSize="13sp" />
</LinearLayout>

4,增加一个无数据时候的空构造方法

package com.mumu.jsrecyclerview1;

import android.support.annotation.Nullable;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

public class TestAdapter extends BaseQuickAdapter<TestEntity.ResultBean.ListBean, BaseViewHolder> {
    /**
     * 构造器,用来初始化TestAdapter
     *
     * @param data 我们的列表数据
     */
    public TestAdapter(@Nullable List<TestEntity.ResultBean.ListBean> data) {
        super(R.layout.item_test, data);
    }

    /**
     * 增加一个构造方法,便于没有数据时候初始化适配器
     */
    public TestAdapter() {
        super(R.layout.item_test);
    }

    /**
     * 继承BaseQuickAdapter后需要重写的方法
     *
     * @param helper view持有者,为重用view而设计,减少每次创建view的内存消耗
     * @param data   我们的列表数据
     */
    @Override
    protected void convert(BaseViewHolder helper, TestEntity.ResultBean.ListBean data) {
        //将每一个需要赋值的id和对应的数据绑定
        helper.setText(R.id.test_item_title, data.getTestTitle())
                .setText(R.id.test_item_message, data.getTestMessage());
    }
}

5,修改了之前默认加载数据的方法,详情看代码注释

package com.mumu.jsrecyclerview1;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.rv_test)
    RecyclerView rvTest;
    @BindView(R.id.srl_test)
    SmartRefreshLayout srlTest;
    private TestAdapter mTestAdapter;
    private ArrayList<TestEntity.ResultBean.ListBean> mTestList;
    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        unbinder = ButterKnife.bind(this);

        initView();
    }

    private void initView() {

        //初始化的时候默认没有数据,显示空布局
        getData(1);
        refreshView();
        smartRefreshView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    /**
     * 刷新消息列表
     */
    private void refreshView() {
        //1,加载空布局文件,便于第五步适配器在没有数据的时候加载
        View emptyView = View.inflate(this, R.layout.empty_view, null);
        //2,设置LayoutManager,LinearLayoutManager表示竖直向下
        rvTest.setLayoutManager(new LinearLayoutManager(this));
        //3,初始化一个无数据的适配器
        mTestAdapter = new TestAdapter();
        //4,绑定recyclerView和适配器
        rvTest.setAdapter(mTestAdapter);
        //5,给recyclerView设置空布局
        mTestAdapter.setEmptyView(emptyView);
        //6,给recyclerView的每一个子列表添加点击事件
        mTestAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Toast.makeText(MainActivity.this, "我点击了第" + position + "个子view",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * MainActivity中增加下拉刷新和上拉加载的监听方法
     */
    private void smartRefreshView() {
        srlTest.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新,一般添加调用接口获取数据的方法
                getData(2);
                refreshLayout.finishRefresh();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //上拉加载,一般添加调用接口获取更多数据的方法
                getData(3);
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });
    }

    /**
     * 获取数据的方法
     * 该方法纯属展示各种效果,实际应用时候请自己根据需求做判断即可
     *
     * @param mode 模式:1为刚开始进来加载数据 空数据 2为下拉刷新 3为上拉加载
     */
    private void getData(int mode) {
        //添加临时数据,一般直接从接口获取
        switch (mode) {
            case 1:

                break;
            case 2:
                mTestList = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    mTestList.add(new TestEntity.ResultBean.ListBean("我有一个小狗", "我有一个小狗我有一个小狗我有一个小狗我有一个小狗我有一个小狗"));
                }
                //更新数据
                mTestAdapter.setNewData(mTestList);
                break;
            case 3:
                for (int i = 0; i < 10; i++) {
                    mTestList.add(new TestEntity.ResultBean.ListBean("我有一个小狗", "我有一个小狗我有一个小狗我有一个小狗我有一个小狗我有一个小狗"));
                }
                mTestAdapter.setNewData(mTestList);
                break;
            default:
                mTestList = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    mTestList.add(new TestEntity.ResultBean.ListBean("我有一个小狗", "我有一个小狗我有一个小狗我有一个小狗我有一个小狗我有一个小狗"));
                }
                break;
        }
    }
}

5,项目结构和github地址

项目结构没有变化,只在xml中增加了一个空的布局文件,demo的地址是同一个,都是在同一个项目迭代。如果需要看前面的项目可以看上一次的提交。

demo地址:https://github.com/mamumu/jsRecyclerView1

如果有发现错误欢迎指正我及时修改,如果有好的建议欢迎留言。谢谢。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容