商城項(xiàng)目實(shí)戰(zhàn) | 11.2 實(shí)現(xiàn)商城分類模塊的一級(jí)目錄和二級(jí)目錄效果(二)

本文為菜鳥窩作者劉婷的連載。”商城項(xiàng)目實(shí)戰(zhàn)”系列來聊聊仿”京東淘寶的購(gòu)物商城”如何實(shí)現(xiàn)。
每個(gè)程序猿必備的110本經(jīng)典編程書,免費(fèi)領(lǐng)取地址:http://mp.weixin.qq.com/s/cx433vAj_CDLzmhOoUS6zA

在文章《商城項(xiàng)目實(shí)戰(zhàn) | 11.1 實(shí)現(xiàn)商城分類模塊的一級(jí)目錄和二級(jí)目錄效果(一)》中已經(jīng)詳細(xì)介紹了一級(jí)目錄的實(shí)現(xiàn),下面就繼續(xù)往下實(shí)現(xiàn)輪播廣告以及二級(jí)目錄的效果,效果圖還是要先來貼一貼的。

效果圖
效果圖

實(shí)現(xiàn)輪播廣告

分類模塊中的輪播廣告效果和主頁(yè)的是一樣的,就使用一樣的方法實(shí)現(xiàn)就可以了。

1. 修改主布局

之前的主布局中只有右側(cè)的一級(jí)目錄 RecyclerView,現(xiàn)在就要添加輪播廣告的控件 SliderLayout。

<?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="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:custom="http://schemas.android.com/tools"
    android:orientation="vertical">
    <com.liuting.cniao_shop.widget.CNiaoToolbar
        android:id="@id/toolbar"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:title="分類"
        android:layout_alignParentTop="true"
        />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="@dimen/basicPaddingTop">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/category_recycler_view_top"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:background="@color/white"
            >

        </android.support.v7.widget.RecyclerView>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="2dp"
            >
            <com.daimajia.slider.library.SliderLayout
                android:id="@+id/category_slider_ads"
                android:layout_width="match_parent"
                android:layout_height="180dp"
                custom:pager_animation="Accordion"
                custom:auto_cycle="true"
                custom:indicator_visibility="visible"
                custom:pager_animation_span="1100"
                />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

2. 請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)

這里的輪播廣告欄所要請(qǐng)求的 Json 數(shù)據(jù)的格式和主頁(yè)的一樣的,所要使用的實(shí)體類也是之前已經(jīng)定義過了的 BannerInfo 對(duì)象,里面包括了 name、imgUrl 和 ID 三個(gè)屬性,實(shí)體類的具體定義就不展示了,直接請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)了。

private void requestBannerData(int type) {

        String url = Constants.API.BANNER+"?type="+type;

        mHttpHelper.get(url, new SpotsCallBack<List<BannerInfo>>(getContext()){


            @Override
            public void onSuccess(Response response, List<BannerInfo> banners) {

                ...
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
            }
        });

    }

輪播廣告的網(wǎng)絡(luò)數(shù)據(jù)的請(qǐng)求寫在了 requestBannerData() 方法中,相應(yīng)地在請(qǐng)求成功 onSuccess() 方法、請(qǐng)求失敗 onFailure() 以及請(qǐng)求出錯(cuò)的 onError() 方法中做處理。

3. 顯示輪播圖片

獲取到了數(shù)據(jù),下面就是要把廣告圖片加載顯示出來。

private void showSliderViews(List<BannerInfo> banners){

        if(banners !=null){

            for (BannerInfo banner : banners){

                DefaultSliderView sliderView = new DefaultSliderView(this.getActivity());
                sliderView.image(banner.getImgUrl());
                sliderView.description(banner.getName());
                sliderView.setScaleType(BaseSliderView.ScaleType.Fit);
                sliderAds.addSlider(sliderView);

            }
        }

        sliderAds.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);

        sliderAds.setCustomAnimation(new DescriptionAnimation());
        sliderAds.setPresetTransformer(SliderLayout.Transformer.Default);
        sliderAds.setDuration(3000);

    }

廣告圖片的顯示加載則寫在了 showSliderViews() 方法中,最后只要把這個(gè)方法寫入網(wǎng)絡(luò)請(qǐng)求成功的 onSuccess() 中就大功告成了。

           @Override
            public void onSuccess(Response response, List<BannerInfo> banners) {

                showSliderViews(banners);
            }

4. 效果圖

運(yùn)行代碼看下輪播廣告的效果圖。

效果圖
效果圖

輪播廣告實(shí)現(xiàn)完成了,接下來就是最后一步,二級(jí)目錄的實(shí)現(xiàn)。

實(shí)現(xiàn)二級(jí)目錄

二級(jí)目錄中是商品的網(wǎng)格列表,還是使用 RecyclerView,不過這次是網(wǎng)格形式的。

1. 修改主布局

在主布局中添加二級(jí)目錄,這里還是使用 RecyclerView。

<?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="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:custom="http://schemas.android.com/tools"
    android:orientation="vertical">
    <com.liuting.cniao_shop.widget.CNiaoToolbar
        android:id="@id/toolbar"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:title="分類"
        android:layout_alignParentTop="true"
        />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="@dimen/basicPaddingTop">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/category_recycler_view_top"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:background="@color/white"
            >

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

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="none">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="2dp"
            >
            <com.daimajia.slider.library.SliderLayout
                android:id="@+id/category_slider_ads"
                android:layout_width="match_parent"
                android:layout_height="180dp"
                custom:pager_animation="Accordion"
                custom:auto_cycle="true"
                custom:indicator_visibility="visible"
                custom:pager_animation_span="1100"
                />
            <com.cjj.MaterialRefreshLayout
                android:id="@+id/category_layout_refresh"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="10dp"
                app:overlay="false"
                app:wave_show="false"
                app:progress_colors="@array/material_colors"
                app:wave_height_type="higher"
                app:progress_show_circle_backgroud="false"
                >
                <com.liuting.cniao_shop.widget.NoScrollRecyclerView
                    android:id="@+id/category_recycler_view_secondary"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                </com.liuting.cniao_shop.widget.NoScrollRecyclerView>

            </com.cjj.MaterialRefreshLayout>
        </LinearLayout>
        </ScrollView>
    </LinearLayout>
</LinearLayout>

2. 定義商品實(shí)體類

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;
    }
}

id 就是商品 ID,name 是商品名稱,imgUrl 是商品圖片的路徑,description 是商品描述,至于 price 就是價(jià)格了。

3. 實(shí)現(xiàn)商品列表 item 布局以及 Adapter

商品列表的布局中需要有圖片實(shí)現(xiàn)、商品名稱以及價(jià)格的顯示,所以布局如下。

<?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="@drawable/selector_list_item"
    android:orientation="vertical"
    android:padding="@dimen/basicPaddingTop">

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/wares_drawee_img"
        android:layout_width="@dimen/ware_grid_img_width"
        android:layout_height="@dimen/ware_grid_img_height"
        android:layout_alignParentLeft="true"
        android:layout_gravity="center"></com.facebook.drawee.view.SimpleDraweeView>

    <TextView
        android:id="@+id/wares_tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:maxLines="3"
        android:textColor="@color/gray"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/wares_tv_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:textColor="@color/crimson"
        android:textSize="18sp" />
</LinearLayout>

item 布局寫好了,就可以實(shí)現(xiàn) Adapter,實(shí)現(xiàn)很簡(jiǎn)單,直接繼承之前已經(jīng)封裝好的 SimpleAdapter。

public class WaresAdapter extends SimpleAdapter<WaresInfo> {

    public WaresAdapter(Context context, List<WaresInfo> datas) {
        super(context, R.layout.grid_item_wares_layout, datas);
    }

    @Override
    protected void convert(BaseViewHolder viewHoder, WaresInfo item) {

        viewHoder.getTextView(R.id.wares_tv_title).setText(item.getName());
        viewHoder.getTextView(R.id.wares_tv_price).setText("¥" + item.getPrice());
        SimpleDraweeView draweeView = (SimpleDraweeView) viewHoder.getView(R.id.wares_drawee_img);
        draweeView.setImageURI(Uri.parse(item.getImgUrl()));
    }
}

這里使用的是 SimpleDraweeView 來顯示圖片,也就是 Fresco 中的圖片組件,具體可以參考文章《商城項(xiàng)目實(shí)戰(zhàn) | 7.1 強(qiáng)大的 Fresco 專為 Android 加載圖片》。

4. 請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)

同樣的將二級(jí)目錄商品列表的數(shù)據(jù)請(qǐng)求寫在一個(gè)單獨(dú)的方法中。

private void requestWares(long categoryId){

        String url = Constants.API.WARES_LIST+"?categoryId="+categoryId+"&curPage="+currPage+"&pageSize="+pageSize;

        mHttpHelper.get(url, new SpotsCallBack<PageInfo<WaresInfo>>(getActivity()) {
            @Override
            public void onError(Response response, int code, Exception e) {
                super.onError(response, code, e);
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
            }

            @Override
            public void onSuccess(Response response, PageInfo<WaresInfo> waresPage) {
                ....

            }
        });
    }

5. 實(shí)現(xiàn)下拉刷新和加載更多

列表數(shù)據(jù)雖然是拿到了,但是有個(gè)問題,那就是要實(shí)現(xiàn)下拉刷新和加載更多,所以我們要先把下拉刷新和加載更多的方法寫好,這里區(qū)分三種狀態(tài),分為正常狀態(tài) STATE_NORMAL,刷新狀態(tài) STATE_REFREH 以及加載更多狀態(tài) STATE_MORE。

private  void refreshData(){

        currPage =1;

        state=STATE_REFREH;
        requestWares(category_id);

    }

刷新數(shù)據(jù)時(shí),需要把當(dāng)前頁(yè)面 currPage 設(shè)置為1,同時(shí)狀態(tài)變?yōu)樗⑿聽顟B(tài) STATE_REFREH,最后請(qǐng)求最新的網(wǎng)絡(luò)數(shù)據(jù)。

而加載更多的實(shí)現(xiàn)就不一樣了。

private void loadMoreData(){

        currPage = ++currPage;
        state = STATE_MORE;
        requestWares(category_id);

    }

加載更多則是不斷往后獲取更多的數(shù)據(jù),當(dāng)前頁(yè)面 currPage 要加1。

6. 顯示商品列表

根據(jù)不同的狀態(tài),來顯示商品列表,刷新時(shí)刷新數(shù)據(jù),加載更多時(shí)獲取更多的數(shù)據(jù),正常狀態(tài)時(shí)初始化數(shù)據(jù)。

private  void showWaresData(List<WaresInfo> wares){

        switch (state){

            case  STATE_NORMAL:

                if(mWaresAdatper ==null) {
                    mWaresAdatper = new WaresAdapter(getContext(), wares);

                    recyclerViewSecondary.setAdapter(mWaresAdatper);

                    recyclerViewSecondary.setLayoutManager(new GridLayoutManager(getContext(), 2));
                    recyclerViewSecondary.setItemAnimator(new DefaultItemAnimator());
                    recyclerViewSecondary.addItemDecoration(new DividerGridItemDecoration(getContext()));
                }
                else{
                    mWaresAdatper.clearData();
                    mWaresAdatper.addData(wares);
                }

                break;

            case STATE_REFREH:
                mWaresAdatper.clearData();
                mWaresAdatper.addData(wares);

                recyclerViewSecondary.scrollToPosition(0);
                layoutRefresh.finishRefresh();
                break;

            case STATE_MORE:
                mWaresAdatper.addData(mWaresAdatper.getDatas().size(),wares);
                recyclerViewSecondary.scrollToPosition(mWaresAdatper.getDatas().size());
                layoutRefresh.finishRefreshLoadMore();
                break;
        }
    }

數(shù)據(jù)的增刪直接調(diào)用寫好的 addData() 方法和 clearData() 就可以了。

7. 一級(jí)目錄與二級(jí)目錄聯(lián)動(dòng)

二級(jí)目錄雖然已經(jīng)可以顯示了,但是還差了一點(diǎn)點(diǎn),那就是和一級(jí)目錄的聯(lián)動(dòng)效果,這也很簡(jiǎn)單了,在一級(jí)目錄列表中添加 item 的點(diǎn)擊事件,然后傳入對(duì)應(yīng)的 category_id,然后調(diào)用請(qǐng)求方法 requestWares() 就可以動(dòng)起來了。

mCategoryAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                TopCategoryInfo category = mCategoryAdapter.getItem(position);

                category_id = category.getId();
                currPage=1;
                state=STATE_NORMAL;
                requestWares(category_id);
            }
        });

根據(jù) category_id 來聯(lián)動(dòng)二級(jí)目錄。

8. 效果圖

獲取到效果圖如下。

效果圖
效果圖

最終效果圖

分類模塊已經(jīng)基本寫好了,最終的效果圖來看下。

效果圖
效果圖

每個(gè)程序猿必備的110本經(jīng)典編程書,免費(fèi)領(lǐng)取地址:http://mp.weixin.qq.com/s/cx433vAj_CDLzmhOoUS6zA

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容