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

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

在上篇文章《商城項(xiàng)目實(shí)戰(zhàn) | 8.1 SwipeRefreshLayout 詳解 官方下拉刷新控件》中對(duì) SwipeRefreshLayout 做了詳細(xì)的介紹了闻妓,但是也發(fā)現(xiàn)了該控件有個(gè)問(wèn)題菌羽,那就是它只支持下拉刷新,不支持加載更多由缆,這在使用的時(shí)候就有點(diǎn)麻煩了注祖,所以本篇文章就要對(duì) SwipeRefreshLayout 進(jìn)行擴(kuò)展猾蒂,使用 SwipeRefreshLayout 實(shí)現(xiàn)可以下拉刷新和加載更多的熱門商品列表。

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

SwipeRefreshLayout 具有下拉刷新的功能是晨,但是加載更多則不支持肚菠,所以就要我們自己擴(kuò)展了,本篇文章就介紹 Github 上面開(kāi)源的一款控件 MaterialRefreshLayout署鸡,這款組件在原本官方的控件 SwipeRefreshLayout 上做了擴(kuò)展案糙,不僅可以支持下拉刷新,還可以支持加載更多靴庆。先來(lái)看下熱門商品的效果圖时捌,如下。

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

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

熱門商品列表實(shí)現(xiàn)過(guò)程

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

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)限

因?yàn)檫@里需要從網(wǎng)絡(luò)請(qǐng)求數(shù)據(jù)亩码,所以需要網(wǎng)絡(luò)權(quán)限。

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

3. 定義布局

根據(jù)效果圖來(lái)設(shè)計(jì) 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="立即購(gòu)買"
            android:layout_gravity="right|bottom"
            />
    </LinearLayout>

</RelativeLayout>

這里圖片加載組件使用的是 Facebook 開(kāi)源的圖片加載組件 Fresco。

4. 初始化 Fresco 類

因?yàn)槭褂昧藞D片加載組件 Fresco惰许,所以必須在 Application 中做對(duì) Fresco 類初始化的處理席覆。

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

5. 定義實(shí)體類

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

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 頁(yè)面信息類卦睹。

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ù)時(shí)調(diào)用。

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

布局、實(shí)體類還有適配器都已經(jīng)寫好了垃环,下面就是要開(kāi)始寫請(qǐ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;

        }
    }

對(duì)于數(shù)據(jù)的請(qǐng)求有三種狀態(tài),分別為 STATE_NORMAL 表示正常狀態(tài)遂庄,STATE_REFREH 表示刷新?tīng)顟B(tài)寥院,STATE_MORE 則表示加載更多的狀態(tài),根據(jù)不同的狀態(tài)下請(qǐng)求數(shù)據(jù)來(lái)執(zhí)行相應(yīng)的操作涛目。

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

下拉刷新時(shí)秸谢,可以直接調(diào)用獲取數(shù)據(jù)方法 getData(),此時(shí)設(shè)置狀態(tài)為 STATE_REFREH 刷新?tīng)顟B(tài)霹肝。

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

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

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

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

10. 初始化 MaterialRefreshLayout

下拉刷新和加載更多的方法都已經(jīng)實(shí)現(xiàn)好了,可以直接初始化 MaterialRefreshLayout 讯赏,然后擴(kuò)展它的刷新事件監(jiān)聽(tīng)和加載更多事件監(jiān)聽(tīng)垮兑,就可以實(shí)現(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)加載完成漱挎,沒(méi)有更多數(shù)據(jù)了",Toast.LENGTH_SHORT).show();
                    layoutRefresh.finishRefreshLoadMore();
                }
            }
        });
    }

最終效果

所有的都實(shí)現(xiàn)好了之后系枪,運(yùn)行代碼,獲取最終效果磕谅。

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

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

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末割疾,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子嘉栓,更是在濱河造成了極大的恐慌宏榕,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件侵佃,死亡現(xiàn)場(chǎng)離奇詭異麻昼,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)馋辈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門抚芦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事叉抡《蓿” “怎么了?”我有些...
    開(kāi)封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵褥民,是天一觀的道長(zhǎng)季春。 經(jīng)常有香客問(wèn)我,道長(zhǎng)消返,這世上最難降的妖魔是什么载弄? 我笑而不...
    開(kāi)封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮撵颊,結(jié)果婚禮上宇攻,老公的妹妹穿的比我還像新娘。我一直安慰自己秦驯,他們只是感情好尺碰,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著译隘,像睡著了一般亲桥。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上固耘,一...
    開(kāi)封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天题篷,我揣著相機(jī)與錄音,去河邊找鬼厅目。 笑死番枚,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的损敷。 我是一名探鬼主播葫笼,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼拗馒!你這毒婦竟也來(lái)了路星?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤诱桂,失蹤者是張志新(化名)和其女友劉穎洋丐,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體挥等,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡友绝,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了肝劲。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片迁客。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡郭宝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出哲泊,到底是詐尸還是另有隱情剩蟀,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布切威,位于F島的核電站育特,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏先朦。R本人自食惡果不足惜缰冤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望喳魏。 院中可真熱鬧棉浸,春花似錦、人聲如沸刺彩。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)创倔。三九已至嗡害,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間畦攘,已是汗流浹背霸妹。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留知押,地道東北人叹螟。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像台盯,于是被迫代替她去往敵國(guó)和親罢绽。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

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