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

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

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

所要實現的熱門商品列表的效果

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

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

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

熱門商品列表實現過程

已經看到了熱門商品列表的效果,下面就是具體的實現過程了。

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. 添加權限

因為這里需要從網絡請求數據,所以需要網絡權限。

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

3. 定義布局

根據效果圖來設計 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. 定義實體類

根據所要請求的數據定義好相應的實體類,這里涉及了兩個實體類,分別為 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() 清除數據以及 addData(List<WaresInfo> datas) 添加數據的方法,為之后刷新數據和加載更多數據時調用。

7. 定義獲取數據的方法

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

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;

        }
    }

對于數據的請求有三種狀態,分別為 STATE_NORMAL 表示正常狀態,STATE_REFREH 表示刷新狀態,STATE_MORE 則表示加載更多的狀態,根據不同的狀態下請求數據來執行相應的操作。

8. 實現下拉刷新方法

下拉刷新時,可以直接調用獲取數據方法 getData(),此時設置狀態為 STATE_REFREH 刷新狀態。

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

9. 實現加載更多的方法

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

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

10. 初始化 MaterialRefreshLayout

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

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(),"已經加載完成,沒有更多數據了",Toast.LENGTH_SHORT).show();
                    layoutRefresh.finishRefreshLoadMore();
                }
            }
        });
    }

最終效果

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

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

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

關于 MaterialRefreshLayout 更多的使用,可以參考Github 源碼

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容