Android中RecyclerView配合BaseRecyclerViewAdapterHelper实现分组布局(六)

今天来使用BaseRecyclerViewAdapterHelper的分组布局功能

说明:

一,使用的Androidstudio版本为3.3.2

二,BaseRecyclerViewAdapterHelper地址如下,使用分组布局功能时adapter是继承BaseSectionQuickAdapter,能实现基本的分组展示,但是他的数据其实是一个列表,由0,1,2....等,适用于展示,不做折叠收缩的列表。可折叠的是继承BaseMultiItemQuickAdapter,这个我下一篇会讲。

三,实现原理简单理解是他吧数据源做了标记,标记这个是头文件,则加载头文件的布局,标记这个是字内容,则加载字内容的布局文件。然后展示出来就是分组的效果。

四,这是BaseRecyclerViewAdapterHelper的系列的第六篇文章,如有简单的不懂使用请看前面的文章。

github地址为:https://github.com/CymChad/BaseRecyclerViewAdapterHelper

展示效果:

https://upload-images.jianshu.io/upload_images/14906070-88e6c7a118dda247.gif?imageMogr2/auto-orient/strip

现在正式开始

1,一般分组布局的后台返回数据格式。

   {
        "Result":[
        {
            "list":[
            {
                "message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"
            },
            {
                "message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"
            }
            ],
            "title":"我有一只小狗"
        },
        {
            "list":[
            {
                "message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"
            }
            ],
            "title":"我有一只小狗"
        }
    ],
        "Success":true,
            "StatusCode":200
    }

2,在build.gradle中增加依赖

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.mumu.jsrecyclerview4"
        minSdkVersion 19
        targetSdkVersion 28
        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:28.0.0'
    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'

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

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

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

3,后台数据的实体对象

package com.mumu.jsrecyclerview4;


import java.io.Serializable;
import java.util.List;

/**
 * @author : zlf
 * date    : 2019/4/15
 * github  : https://github.com/mamumu
 * blog    : https://www.jianshu.com/u/281e9668a5a6
 */
public class TestEntity implements Serializable {

//    {
//        "Result":[
//        {
//            "list":[
//            {
//                "message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"
//            },
//            {
//                "message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"
//            }
//            ],
//            "title":"我有一只小狗"
//        },
//        {
//            "list":[
//            {
//                "message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"
//            }
//            ],
//            "title":"我有一只小狗"
//        }
//    ],
//        "Success":true,
//            "StatusCode":200
//    }

    /**
     * Result : [{"list":[{"message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"},{"message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"}],"title":"我有一只小狗"},{"list":[{"message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"}],"title":"我有一只小狗"}]
     * Success : true
     * StatusCode : 200
     */

    private boolean Success;
    private int StatusCode;
    private List<ResultBean> Result;

    public boolean isSuccess() {
        return Success;
    }

    public void setSuccess(boolean Success) {
        this.Success = Success;
    }

    public int getStatusCode() {
        return StatusCode;
    }

    public void setStatusCode(int StatusCode) {
        this.StatusCode = StatusCode;
    }

    public List<ResultBean> getResult() {
        return Result;
    }

    public void setResult(List<ResultBean> Result) {
        this.Result = Result;
    }

    public static class ResultBean {
        /**
         * list : [{"message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"},{"message":"我有一只小狗我有一只小狗我有一只小狗我有一只小狗"}]
         * title : 我有一只小狗
         */

        private String title;
        private List<ListBean> list;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public static class ListBean {
            /**
             * message : 我有一只小狗我有一只小狗我有一只小狗我有一只小狗
             */

            private String message;

            public String getMessage() {
                return message;
            }

            public void setMessage(String message) {
                this.message = message;
            }
        }
    }
}

4,对应的适配器

package com.mumu.jsrecyclerview4;

import android.view.View;
import android.widget.Toast;

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

import java.util.List;

/**
 * @author : zlf
 * date    : 2019/4/15
 * github  : https://github.com/mamumu
 * blog    : https://www.jianshu.com/u/281e9668a5a6
 * 说明:自命名适配器,继承BaseSectionQuickAdapter<SectionTestEntity, BaseViewHolder>为固定写法,然后实现构造器和需要重写的方法
 * convertHead: 为头部赋值 本文中红色字体为头部,头部中一般是只有一项为 item.header,如若要在头部中增加内容需要固定内容
 * convert: 为子内容赋值,本文中蓝色背景为字内容,字内容可以多个赋值为item.t,是一个后台返回的列表
 */
public class TestAdapter extends BaseSectionQuickAdapter<SectionTestEntity, BaseViewHolder> {


    public TestAdapter(int layoutResId, int sectionHeadResId, List<SectionTestEntity> data) {
        super(layoutResId, sectionHeadResId, data);
    }

    @Override
    protected void convertHead(BaseViewHolder helper, SectionTestEntity item) {
        helper.setText(R.id.test_item_title, item.header);
        helper.setVisible(R.id.more, item.isMore());
        helper.addOnClickListener(R.id.more);
    }

    @Override
    protected void convert(BaseViewHolder helper, SectionTestEntity item) {
        TestEntity.ResultBean.ListBean listBean = item.t;
        helper.setText(R.id.test_item_message, listBean.getMessage());

    }
}

5,对应的主activity

package com.mumu.jsrecyclerview4;

import android.app.Activity;
import android.app.AppComponentFactory;
import android.support.annotation.NonNull;
import android.os.Bundle;
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.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Vector;

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

/**
 * @author : zlf
 * date    : 2019/4/15
 * github  : https://github.com/mamumu
 * blog    : https://www.jianshu.com/u/281e9668a5a6
 */
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> mResult=new ArrayList<>();
    private ArrayList<SectionTestEntity> sectionTestEntity;
    private Unbinder unbinder;

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

    /**
     * 模拟后台数据返回
     */
    private void initData() {
        for (int i = 0; i < 2; i++) {
            TestEntity.ResultBean resultBean = new TestEntity.ResultBean();
            resultBean.setTitle("我有一只小狗" + i);
            List<TestEntity.ResultBean.ListBean> list = new ArrayList<>();
            for (int j = 0; j < 3; j++) {
                TestEntity.ResultBean.ListBean listBean = new TestEntity.ResultBean.ListBean();
                listBean.setMessage("我有一只小狗我有一只小狗我有一只小狗我有一只小狗" + j);
                list.add(listBean);
            }
            resultBean.setList(list);
            mResult.add(resultBean);
        }
    }

    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(R.layout.item_test_list,R.layout.item_test_head,null);
        //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) {
                SectionTestEntity s=sectionTestEntity.get(position);
                if(s.isHeader){
                    Toast.makeText(MainActivity.this, "点击了第"+position+s.header,
                            Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "点击了第"+position+s.t.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }

            }
        });
        mTestAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Toast.makeText(MainActivity.this, "点击了第"+position+"onItemChildClick" + position, Toast.LENGTH_LONG).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();
                //结束上拉加载
                refreshLayout.finishLoadMore();
            }
        });
    }

    /**
     * 获取数据的方法
     * 该方法纯属展示各种效果,实际应用时候请自己根据需求做判断即可
     *
     * @param mode 模式:1为刚开始进来加载数据 空数据 2为下拉刷新 3为上拉加载
     */
    private void getData(int mode) {
        //添加临时数据,一般直接从接口获取
        switch (mode) {
            case 1:
                break;
            case 2:
                sectionTestEntity=new ArrayList<>();
                for(int i=0;i<mResult.size();i++){
                    SectionTestEntity header=new SectionTestEntity(true,mResult.get(i).getTitle(),true);
                    sectionTestEntity.add(header);
                    for(int j=0;j<mResult.get(i).getList().size();j++){
                        SectionTestEntity content=new SectionTestEntity(mResult.get(i).getList().get(j));
                        sectionTestEntity.add(content);
                    }
                }
                //更新数据
                mTestAdapter.setNewData(sectionTestEntity);
                break;
            case 3:
                for(int i=0;i<mResult.size();i++){
                    SectionTestEntity header=new SectionTestEntity(true,mResult.get(i).getTitle(),true);
                    sectionTestEntity.add(header);
                    for(int j=0;j<mResult.get(i).getList().size();j++){
                        SectionTestEntity content=new SectionTestEntity(mResult.get(i).getList().get(j));
                        sectionTestEntity.add(content);
                    }
                }
                //更新数据
                mTestAdapter.setNewData(sectionTestEntity);
                break;
        }
    }
}

6,MainActivity对应的布局

<?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: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>

7,刚开始加载的空布局

<?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>

8,两个子布局,头部和子内容的

<?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="wrap_content"
    android:background="#FFFFFF"
    android:orientation="horizontal"
    android:paddingLeft="15dp"
    android:paddingRight="15dp">

    <TextView
        android:id="@+id/test_item_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:text="我爱小狗"
        android:textColor="@color/colorAccent"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/more"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:paddingRight="10dp"
        android:gravity="right|center"
        android:textColor="@color/colorAccent"
        android:text="more >"
        android:textSize="18sp"/>
</LinearLayout>
<?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:background="#6ffff6"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingLeft="15dp"
    android:paddingRight="15dp">

    <TextView
        android:id="@+id/test_item_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/test_item_title"
        android:ellipsize="end"
        android:maxLines="2"
        android:text="我爱小狗我爱小狗我爱小狗我爱小狗我爱小狗我爱小狗我爱小狗我爱小狗我爱小狗我爱小狗"
        android:textColor="#000000"
        android:textSize="14sp" />
</LinearLayout>

9,SectionTestEntity主要作用是展示头部中more的展示

package com.mumu.jsrecyclerview4;

import com.chad.library.adapter.base.entity.SectionEntity;

/**
 * @author : zlf
 * date    : 2019/4/15
 * github  : https://github.com/mamumu
 * blog    : https://www.jianshu.com/u/281e9668a5a6
 */
public class SectionTestEntity extends SectionEntity<TestEntity.ResultBean.ListBean> {
    private boolean isMore=true;
    public SectionTestEntity(boolean isHeader, String header,boolean isMore) {
        super(isHeader, header);
        this.isMore = isMore;
    }

    public SectionTestEntity(TestEntity.ResultBean.ListBean listBean) {
        super(listBean);
    }

    public boolean isMore() {
        return isMore;
    }

    public void setMore(boolean more) {
        isMore = more;
    }
}

10,对应github地址

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

10,本系列第一篇文章地址,如果本文看不懂可以看第一篇,如有其它疑问请留言。

地址:https://www.jianshu.com/p/ce972355c71d

如果有发现错误欢迎指正我及时修改,如果有好的建议欢迎留言。如果觉得对你有帮助欢迎给小星星,谢谢。

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

推荐阅读更多精彩内容