商城項目實戰(zhàn) | 8.2 SwipeRefreshLayout 實現(xiàn)可以下拉刷新和加載更多的熱門商品列表

本文為菜鳥窩作者劉婷的連載。”商城項目實戰(zhàn)”系列來聊聊仿”京東淘寶的購物商城”如何實現(xiàn)。
140套Android優(yōu)秀開源項目源碼,領(lǐng)取地址:http://mp.weixin.qq.com/s/afPGHqfdiApALZqHsXbw-A
或歡迎勾搭運營小姐姐(微信 id:BT474849)免費領(lǐng)取哦~

在上篇文章《商城項目實戰(zhàn) | 8.1 SwipeRefreshLayout 詳解 官方下拉刷新控件》中對 SwipeRefreshLayout 做了詳細的介紹了,但是也發(fā)現(xiàn)了該控件有個問題,那就是它只支持下拉刷新,不支持加載更多,這在使用的時候就有點麻煩了,所以本篇文章就要對 SwipeRefreshLayout 進行擴展,使用 SwipeRefreshLayout 實現(xiàn)可以下拉刷新和加載更多的熱門商品列表。

所要實現(xiàn)的熱門商品列表的效果

SwipeRefreshLayout 具有下拉刷新的功能,但是加載更多則不支持,所以就要我們自己擴展了,本篇文章就介紹 Github 上面開源的一款控件 MaterialRefreshLayout,這款組件在原本官方的控件 SwipeRefreshLayout 上做了擴展,不僅可以支持下拉刷新,還可以支持加載更多。先來看下熱門商品的效果圖,如下。

[圖片上傳失敗...(image-c731af-1565145810083)]

圖中的熱門商品列表可以下拉刷新數(shù)據(jù),同時還需要加載更多的功能,如何實現(xiàn)這樣的熱門商品列表的效果呢?帶著這個問題往下看。

熱門商品列表實現(xiàn)過程

已經(jīng)看到了熱門商品列表的效果,下面就是具體的實現(xiàn)過程了。

1. Gradle 添加依賴

在 module 下的 build.gradle 文件中添加所需第三方控件的依賴。

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.daimajia.slider:library:1.1.5@aar'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.android.support:recyclerview-v7:25.2.0'
    compile 'com.android.support:cardview-v7:25.2.0'
    compile 'com.squareup.okhttp3:okhttp:3.6.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.github.d-max:spots-dialog:0.7'
    compile 'com.facebook.fresco:fresco:1.2.0'
    compile 'com.cjj.materialrefeshlayout:library:1.3.0'
}

2. 添加權(quán)限

因為這里需要從網(wǎng)絡(luò)請求數(shù)據(jù),所以需要網(wǎng)絡(luò)權(quán)限。

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

3. 定義布局

根據(jù)效果圖來設(shè)計 RecyclerView 的 item 布局以及 熱門模塊 HotFragment 的布局。
首先是新建 xml 布局文件 fragment_hot_layout.xml,也就是熱門模塊 HotFragment 的布局,如下。

<?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"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.cjj.MaterialRefreshLayout
        android:id="@+id/hot_layout_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp"
        app:overlay="true"
        app:wave_show="true"
        app:wave_color="#90ffffff"
        app:progress_colors="@array/material_colors"
        app:wave_height_type="higher"
        >

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

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

    </com.cjj.MaterialRefreshLayout>

</LinearLayout>

然后就是RecyclerView 的 item 布局了。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/selector_list_item"
    android:padding="5dp"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.facebook.drawee.view.SimpleDraweeView
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:background="@null"
        android:id="@+id/drawee_view"
        android:layout_alignParentLeft="true"
        app:viewAspectRatio="1"
        >
    </com.facebook.drawee.view.SimpleDraweeView>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/drawee_view">

        <TextView
            android:id="@+id/text_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="16sp"
            android:maxLines="3"
            />

        <TextView
            android:id="@+id/text_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textColor="@color/firebrick"
            />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/bigRedButton"
            android:layout_marginTop="20dp"
            android:text="立即購買"
            android:layout_gravity="right|bottom"
            />
    </LinearLayout>

</RelativeLayout>

這里圖片加載組件使用的是 Facebook 開源的圖片加載組件 Fresco。

4. 初始化 Fresco 類

因為使用了圖片加載組件 Fresco,所以必須在 Application 中做對 Fresco 類初始化的處理。

public class CNiaoApplicaiton extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    }
}

5. 定義實體類

根據(jù)所要請求的數(shù)據(jù)定義好相應(yīng)的實體類,這里涉及了兩個實體類,分別為 WaresInfo 商品信息類以及 PageInfo 頁面信息類。

WaresInfo 商品信息類如下。

public class WaresInfo implements Serializable{
    private Long id;
    private String name;
    private String imgUrl;
    private String description;
    private Float price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }
}

下面就是 PageInfo 頁面信息類。

public class PageInfo <T> implements Serializable{
    private  int currentPage;
    private  int pageSize;
    private  int totalPage;
    private  int totalCount;

    private List<T> list;

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

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

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

6. 定義 Adapter

RecyclerView 作為列表控件,必定需要適配器 Adapter,下面是定義的 HotWaresAdapter。

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

    private List<WaresInfo> mDatas;

    private LayoutInflater mInflater;

    public HotWaresAdapter(List<WaresInfo> wares){
        mDatas = wares;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mInflater = LayoutInflater.from(parent.getContext());
        View view = mInflater.inflate(R.layout.recycler_item_wares_layout,null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        WaresInfo wares = getData(position);
        holder.draweeView.setImageURI(Uri.parse(wares.getImgUrl()));
        holder.textTitle.setText(wares.getName());
        holder.textPrice.setText("¥"+wares.getPrice());
    }

    public WaresInfo getData(int position){

        return mDatas.get(position);
    }

    public List<WaresInfo> getDatas(){

        return  mDatas;
    }
    public void clearData(){

        mDatas.clear();
        notifyItemRangeRemoved(0,mDatas.size());
    }

    public void addData(List<WaresInfo> datas){

        addData(0,datas);
    }

    public void addData(int position,List<WaresInfo> datas){

        if(datas !=null && datas.size()>0) {

            mDatas.addAll(datas);
            notifyItemRangeChanged(position, mDatas.size());
        }
    }

    @Override
    public int getItemCount() {

        if(mDatas!=null && mDatas.size()>0)
            return mDatas.size();
        return 0;
    }



    class ViewHolder extends RecyclerView.ViewHolder{
        SimpleDraweeView draweeView;
        TextView textTitle;
        TextView textPrice;
        public ViewHolder(View itemView) {
            super(itemView);

            draweeView = (SimpleDraweeView) itemView.findViewById(R.id.drawee_view);
            textTitle= (TextView) itemView.findViewById(R.id.text_title);
            textPrice= (TextView) itemView.findViewById(R.id.text_price);
        }
    }
}

在 Adapter 中寫入了 clearData() 清除數(shù)據(jù)以及 addData(List<WaresInfo> datas) 添加數(shù)據(jù)的方法,為之后刷新數(shù)據(jù)和加載更多數(shù)據(jù)時調(diào)用。

7. 定義獲取數(shù)據(jù)的方法

布局、實體類還有適配器都已經(jīng)寫好了,下面就是要開始寫請求數(shù)據(jù)的方法了。

private void getData(){

        String url = Constants.API.WARES_HOT+"?curPage="+currPage+"&pageSize="+pageSize;
        httpHelper.get(url, new SpotsCallBack<PageInfo<WaresInfo>>(getContext()) {
            @Override
            public void onSuccess(Response response, PageInfo<WaresInfo> waresPage) {
                datas = waresPage.getList();
                currPage = waresPage.getCurrentPage();
                totalPage =waresPage.getTotalPage();
                showData();
            }

            @Override
            public void onError(Response response, int code, Exception e) {
                Toast.makeText(getActivity(),"Error:"+code+e.toString(),Toast.LENGTH_SHORT).show();
                super.onError(response,code,e);
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                Toast.makeText(getActivity(),"Fail:"+e.toString(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    private  void showData(){

        switch (state){

            case  STATE_NORMAL:
                mAdatper = new HotWaresAdapter(datas);

                recyclerView.setAdapter(mAdatper);

                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                recyclerView.addItemDecoration(new WareItemDecoration(getContext(),WareItemDecoration.VERTICAL_LIST));

                break;

            case STATE_REFREH:
                mAdatper.clearData();
                mAdatper.addData(datas);
                recyclerView.scrollToPosition(0);
                layoutRefresh.finishRefresh();
                break;

            case STATE_MORE:
                mAdatper.addData(mAdatper.getDatas().size(),datas);
                recyclerView.scrollToPosition(mAdatper.getDatas().size());
                layoutRefresh.finishRefreshLoadMore();
                break;

        }
    }

對于數(shù)據(jù)的請求有三種狀態(tài),分別為 STATE_NORMAL 表示正常狀態(tài),STATE_REFREH 表示刷新狀態(tài),STATE_MORE 則表示加載更多的狀態(tài),根據(jù)不同的狀態(tài)下請求數(shù)據(jù)來執(zhí)行相應(yīng)的操作。

8. 實現(xiàn)下拉刷新方法

下拉刷新時,可以直接調(diào)用獲取數(shù)據(jù)方法 getData(),此時設(shè)置狀態(tài)為 STATE_REFREH 刷新狀態(tài)。

private  void refreshData(){
        currPage =1;
        state=STATE_REFREH;
        getData();
    }

9. 實現(xiàn)加載更多的方法

同樣的,加載更多其實就是和下拉刷新狀態(tài)有所不同,也是直接調(diào)用獲取數(shù)據(jù)方法 getData(),此時設(shè)置狀態(tài)為 STATE_MORE 加載更多狀態(tài)。

private void loadMoreData(){
        currPage = ++currPage;
        state = STATE_MORE;
        getData();
    }

10. 初始化 MaterialRefreshLayout

下拉刷新和加載更多的方法都已經(jīng)實現(xiàn)好了,可以直接初始化 MaterialRefreshLayout ,然后擴展它的刷新事件監(jiān)聽和加載更多事件監(jiān)聽,就可以實現(xiàn)我們所需要的效果了。

private  void initRefreshLayout(){

        layoutRefresh.setLoadMore(true);
        layoutRefresh.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {

                refreshData();

            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {

                if(currPage <=totalPage)
                    loadMoreData();
                else{
                    Toast.makeText(getActivity(),"已經(jīng)加載完成,沒有更多數(shù)據(jù)了",Toast.LENGTH_SHORT).show();
                    layoutRefresh.finishRefreshLoadMore();
                }
            }
        });
    }

最終效果

所有的都實現(xiàn)好了之后,運行代碼,獲取最終效果。

[圖片上傳失敗...(image-1189c0-1565145810084)]

最終基本實現(xiàn)了文章開始所要求的可以下拉刷新和加載更多的熱門商品列表的效果。

關(guān)于 MaterialRefreshLayout 更多的使用,可以參考Github 源碼

【五一大促】菜鳥窩全場android項目實戰(zhàn)課程低至五折,更有價值33元的四款熱門技術(shù)免費領(lǐng),17年初優(yōu)惠力度最大的一次活動,有意向的童鞋不要錯過
狂戳>>http://www.cniao5.com/hd/2017/51.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,106評論 6 542
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,441評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,211評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,736評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,475評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,834評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,829評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,009評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,559評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,306評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,516評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,038評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,728評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,132評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,443評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,249評論 3 399
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,484評論 2 379

推薦閱讀更多精彩內(nèi)容