1. 程式人生 > >無限輪播(Handler+ImageLoader)+OkHttp二次封裝

無限輪播(Handler+ImageLoader)+OkHttp二次封裝

今天來搞一下通過網路請求實現無限輪播,我寫了一個小demo與大家分享一下,我是在fragment中操作的,那麼Activity在這裡就不展示了,Activity也就是實現fragment與fragment之間的聯動,所以今天就只給大家分享一下輪播圖涉及到的一些相關程式碼,節省大家的閱讀時間,提高大家的工作效率;
首先搭建環境:
依賴:

 /*android5.0的新特性使用*/
    implementation 'com.android.support:support-v13:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0' implementation 'com.android.support:support-v13:28.0.0' implementation 'com.squareup.okhttp3:okhttp:3.4.2' implementation 'com.android.support:recyclerview-v7:28.0.0' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

網路許可權:

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

因為本次我採用的是ImageLoader載入圖片,所以需要在AndroidManifest(清單檔案)裡註冊一下我們自定義的MyApplication類:

 <application
        android:name=".MyApp.MyApplication"
    </application>

1.Fragment:
在這裡我呼叫了封裝好的OkHttp進行網路請求,從而獲取圖片,通過handler實現無限輪播

package com.example.weekone.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.weekone.R;
import com.example.weekone.adapter.SlideshowAdadpter;
import com.example.weekone.bean.DataItem;
import com.example.weekone.util.OkHttpUtils;
import com.google.gson.Gson;

import java.util.List;

/**
 * date:2018/12/2
 * author:李壯(大壯)
 * function:
 */
public class HomeFragment extends Fragment {
    private ViewPager home_vp;
    private RecyclerView home_center_recyclerview;
    private RecyclerView home_bootom_recyclerview;
    private String path = "http://result.eolinker.com/umIPmfS6c83237d9c70c7c9510c9b0f97171a308d13b611?uri=homepage";
    private SlideshowAdadpter mSlideshowAdadpter;
    private int SUM = 0;

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            home_vp.setCurrentItem(home_vp.getCurrentItem() + 1);
            mHandler.sendEmptyMessageDelayed(SUM,1000);
        }
    };
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getContext(), R.layout.home_fragment_item, null);
        //初始化控制元件
        initView(view);

        //載入輪播圖
        initSlideshow();

        return view;
    }

    //設定輪播效果
    private void initSlideshow() {
        OkHttpUtils.getInstance().doGet(path, new OkHttpUtils.onOkCallback() {
            @Override
            public void success(String json) {
                DataItem dataItem = new Gson().fromJson(json, DataItem.class);
                List<DataItem.DataBean.DefaultGoodsListBean> defaultGoodsList = dataItem.getData().getDefaultGoodsList();
                //建立介面卡
                mSlideshowAdadpter = new SlideshowAdadpter(getActivity());
                mSlideshowAdadpter.setData(defaultGoodsList);
                home_vp.setAdapter(mSlideshowAdadpter);
                mHandler.sendEmptyMessageDelayed(SUM,1000);
            }

            @Override
            public void defeated(Exception e) {

            }
        });
    }

    private void initView(View view) {
        home_vp = (ViewPager) view.findViewById(R.id.home_vp);
        home_center_recyclerview = (RecyclerView) view.findViewById(R.id.home_center_recyclerview);
        home_bootom_recyclerview = (RecyclerView) view.findViewById(R.id.home_bootom_recyclerview);
    }
}

2.建立介面卡:
在這裡對頁面進行操作,完成圖片的展示,我採用了一個比較簡單的框架ImageLoader來進行圖片的載入展示工作

package com.example.weekone.adapter;

import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.weekone.MyApp.Config;
import com.example.weekone.bean.DataItem;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * date:2018/12/2
 * author:李壯(大壯)
 * function:輪播圖介面卡
 */
public class SlideshowAdadpter extends PagerAdapter {

    private Context mContext;
    private List<DataItem.DataBean.DefaultGoodsListBean> mDefaultGoodsListBeans;
    private String path = "http://result.eolinker.com/umIPmfS6c83237d9c70c7c9510c9b0f97171a308d13b611?uri=homepage";

    public SlideshowAdadpter(Context context) {
        this.mContext = context;
        mDefaultGoodsListBeans = new ArrayList<>();
    }
    public void setData(List<DataItem.DataBean.DefaultGoodsListBean> defaultGoodsList) {
        mDefaultGoodsListBeans.clear();
        if (defaultGoodsList != null){
            mDefaultGoodsListBeans.addAll(defaultGoodsList);
        }
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return mDefaultGoodsListBeans.size() > 0 ? Integer.MAX_VALUE : 0;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        //SimpleDraweeView simpleDraweeView = new SimpleDraweeView(mContext);
        ImageView imageView = new ImageView(mContext);
        //Uri parse = Uri.parse(mDefaultGoodsListBeans.get(position).getGoods_img());
        //GenericDraweeHierarchyBuilder genericDraweeHierarchyBuilder = new GenericDraweeHierarchyBuilder(mContext.getResources());
        ImageLoader.getInstance().displayImage(mDefaultGoodsListBeans.get(position % mDefaultGoodsListBeans.size()).getGoods_img(),imageView,Config.disPlay());
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}

3.建立自定義類MyApplication:
前面提到我使用的是ImageLoader所以我們需要自定義一個MyApplication類

package com.example.weekone.MyApp;

import android.app.Application;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

/**
 * date:2018/12/2
 * author:李壯(大壯)
 * function:
 */
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);

        ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(this)
                .diskCacheSize(50*1024*1024)
                .memoryCacheSize(10)
                .defaultDisplayImageOptions(Config.disPlay())
                .build();
        ImageLoader.getInstance().init(imageLoaderConfiguration);
    }
}

接下來定義一個樣式類:
我們可以根據需求,設定相應的展示樣式,這次我就搞個簡單的,使用的是介面提供的預設樣式的圖片效果

package com.example.weekone.MyApp;

import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * date:2018/12/2
 * author:李壯(大壯)
 * function:
 */
public class Config {
    public static DisplayImageOptions  disPlay(){
        DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheInMemory(true)
                .build();
        return displayImageOptions;
    }
}

4.OkHttp二次封裝

package com.example.weekone.util;

import android.os.Handler;
import android.os.Looper;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * date:2018/12/2
 * author:李壯(大壯)
 * function:OkHttp二次封裝
 */
public class OkHttpUtils {

    private static OkHttpUtils mOkHttpUtils;
    private final OkHttpClient mOkHttpClient;
    private Handler mHandler;

    //建立一個私有的構造方法
    private OkHttpUtils() {
        //建立一個主執行緒Handler
        mHandler = new Handler(Looper.getMainLooper());
        //建立OkHttpClient
        mOkHttpClient = new OkHttpClient.Builder()
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .connectTimeout(10,TimeUnit.SECONDS)
                .build();
    }

    //單例模式
    public static OkHttpUtils getInstance(){
       if (mOkHttpUtils == null){
           synchronized (OkHttpUtils.class){
               if (mOkHttpUtils == null){
                   mOkHttpUtils = new OkHttpUtils();
               }
           }
       }
       return mOkHttpUtils;
    }

    //介面回撥
    public interface onOkCallback{
        //成功
        void success(String json);
        //失敗
        void defeated(Exception e);
    }

    //封裝doPost網路請求
    public void doPost(String url, Map<String,String> map, final onOkCallback okCallback){
        //建立一個FormBody
        FormBody.Builder builder = new FormBody.Builder();
        if (map != null){
            for (String key : map.keySet()){
                builder.add(key,map.get(key));
            }
        }

        FormBody formBody = builder.build();

        //建立Request
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        //建立Call物件
        Call call = mOkHttpClient.newCall(request);
        //通過call呼叫enqueue方法,完成網路請求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (okCallback != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            okCallback.defeated(e);
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()){
                    final String json = response.body().string();
                    if (okCallback != null){
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                okCallback.success(json);
                            }
                        });
                    }
                }
            }
        });

    }

    //封裝doGet網路請求
    public void doGet(String url,final onOkCallback okCallback){
        //建立Request
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        //建立Call物件
        Call call = mOkHttpClient.newCall(request);
        //通過call呼叫enqueue方法,完成網路請求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (okCallback != null){
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            okCallback.defeated(e);
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()){
                    final String json = response.body().string();
                    if (okCallback != null){
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                okCallback.success(json);
                            }
                        });
                    }
                }
            }
        });

    }
}

5.Bean類:

package com.example.weekone.bean;

import java.util.List;

public class DataItem {


    private int code;
    private String msg;
    private DataBean data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public static class DataBean {
       

        private ActivityInfoBean activityInfo;
        private boolean creditRecived;
        private GoodsSpreeActivityBean goodsSpreeActivity;
        private List<SubjectsBean> subjects;
        private List<Ad1Bean> ad1;
        private List<Ad5Bean> ad5;
        private List<Ad8Bean> ad8;
        private List<DefaultGoodsListBean> defaultGoodsList;

        public ActivityInfoBean getActivityInfo() {
            return activityInfo;
        }

        public void setActivityInfo(ActivityInfoBean activityInfo) {
            this.activityInfo = activityInfo;
        }

        public boolean isCreditRecived() {
            return creditRecived;
        }

        public void setCreditRecived(boolean creditRecived) {
            this.creditRecived = creditRecived;
        }

        public GoodsSpreeActivityBean getGoodsSpreeActivity() {
            return goodsSpreeActivity;
        }

        public void setGoodsSpreeActivity(GoodsSpreeActivityBean goodsSpreeActivity) {
            this.goodsSpreeActivity = goodsSpreeActivity;
        }

        public List<SubjectsBean> getSubjects() {
            return subjects;
        }

        public void setSubjects(List<SubjectsBean> subjects) {
            this.subjects = subjects;
        }

        public List<Ad1Bean> getAd1() {
            return ad1;
        }

        public void setAd1(List<Ad1Bean> ad1) {
            this.ad1 = ad1;
        }

        public List<Ad5Bean> getAd5() {
            return ad5;
        }

        public void setAd5(List<Ad5Bean> ad5) {
            this.ad5 = ad5;
        }

        public List<Ad8Bean> getAd8() {
            return ad8;
        }

        public void setAd8(List<Ad8Bean> ad8) {
            this.ad8 = ad8;
        }

        public List<DefaultGoodsListBean> getDefaultGoodsList() {
            return defaultGoodsList;
        }

        public void setDefaultGoodsList(List<DefaultGoodsListBean> defaultGoodsList) {
            this.defaultGoodsList = defaultGoodsList;
        }

        public static class ActivityInfoBean {
           

            private String activityAreaDisplay;
            private List<ActivityInfoListBean> activityInfoList;

            public String getActivityAreaDisplay() {
                return activityAreaDisplay;
            }

            public void setActivityAreaDisplay(String activityAreaDisplay) {
                this.activityAreaDisplay = activityAreaDisplay;
            }

            public List<ActivityInfoListBean> getActivityInfoList() {
                return activityInfoList;
            }

            public void setActivityInfoList(List<ActivityInfoListBean> activityInfoList) {
                this.activityInfoList = activityInfoList;
            }

            public static class ActivityInfoListBean {
               

                private String id;
                private String activityImg;
                private String activityType;
                private String activityData;
                private String activityDataDetail;
                private String activityAreaDisplay;
                private String countDownEnable;
                private String remark;
                private int sort;

                public String getId() {
                    return id;
                }

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

                public String getActivityImg() {
                    return activityImg;
                }

                public void setActivityImg(String activityImg) {
                    this.activityImg = activityImg;
                }

                public String getActivityType() {
                    return activityType;
                }

                public void setActivityType(String activityType) {
                    this.activityType = activityType;
                }

                public String getActivityData() {
                    return activityData;
                }

                public void setActivityData(String activityData) {
                    this.activityData = activityData;
                }

                public String getActivityDataDetail() {
                    return activityDataDetail;
                }

                public void setActivityDataDetail(String activityDataDetail) {
                    this.activityDataDetail = activityDataDetail;
                }

                public String getActivityAreaDisplay() {
                    return activityAreaDisplay;
                }

                public void setActivityAreaDisplay(String activityAreaDisplay) {
                    this.activityAreaDisplay = activityAreaDisplay;
                }

                public String getCountDownEnable() {
                    return countDownEnable;
                }

                public void setCountDownEnable(String countDownEnable) {
                    this.countDownEnable = countDownEnable;
                }

                public String getRemark() {
                    return remark;
                }

                public void setRemark(String remark) {
                    this.remark = remark;
                }

                public int getSort() {
                    return sort;
                }

                public void setSort(int sort) {
                    this.sort = sort;
                }
            }
        }

        public static class GoodsSpreeActivityBean {
        

            private String id;
            private String name;
            private String startDate;
            private String endDate;
            private String status;
            private String startSeconds;
            private String endSeconds;
            private String isChecked;
            private List<GoodsListBean> goodsList;

            public String getId() {
                return id;
            }

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

            public String getName() {
                return name;
            }

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

            public String getStartDate() {
                return startDate;
            }

            public void setStartDate(String startDate) {
                this.startDate = startDate;
            }

            public String getEndDate() {
                return endDate;
            }

            public void setEndDate(String endDate) {
                this.endDate = endDate;
            }

            public String getStatus() {
                return status;
            }

            public void setStatus(String status) {
                this.status = status;
            }

            public String getStartSeconds() {
                return startSeconds;
            }

            public void setStartSeconds(String startSeconds) {
                this.startSeconds = startSeconds;
            }

            public String getEndSeconds() {
                return endSeconds;
            }

            public void setEndSeconds(String endSeconds) {
                this.endSeconds = endSeconds;
            }

            public String getIsChecked() {
                return isChecked;
            }

            public void setIsChecked(String isChecked) {
                this.isChecked = isChecked;
            }

            public List<GoodsListBean> getGoodsList() {
                return goodsList;
            }

            public void setGoodsList(List<GoodsListBean> goodsList) {
                this.goodsList = goodsList;
            }

            public static class GoodsListBean {
               

                private String id;
                private String goodsSpreeId;
                private String goodsId;
                private String goodsName;
                private String goodsImg;
                private int marketPrice;
                private double activityPrice;
                private int salesRatio;
                private int stockNumber;
                private int releaseNumber;

                public String getId() {
                    return id;
                }

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

                public String getGoodsSpreeId() {
                    return goodsSpreeId;
                }

                public void setGoodsSpreeId(String goodsSpreeId) {
                    this.goodsSpreeId = goodsSpreeId;
                }

                public String getGoodsId() {
                    return goodsId;
                }

                public void setGoodsId(String goodsId) {
                    this.goodsId = goodsId;
                }

                public String getGoodsName() {
                    return goodsName;
                }

                public void setGoodsName(String goodsName) {
                    this.goodsName = goodsName;
                }

                public String getGoodsImg() {
                    return goodsImg;
                }

                public void setGoodsImg(String goodsImg) {
                    this.goodsImg = goodsImg;
                }

                public int getMarketPrice() {
                    return marketPrice;
                }

                public void setMarketPrice(int marketPrice) {
                    this.marketPrice = marketPrice;
                }

                public double getActivityPrice() {
                    return activityPrice;
                }

                public void setActivityPrice(double activityPrice) {
                    this.activityPrice = activityPrice;
                }

                public int getSalesRatio() {
                    return salesRatio;
                }

                public void setSalesRatio(int salesRatio) {
                    this.salesRatio = salesRatio;
                }

                public int getStockNumber() {
                    return stockNumber;
                }

                public void setStockNumber(int stockNumber) {
                    this.stockNumber = stockNumber;
                }

                public int getReleaseNumber() {
                    return releaseNumber;
                }

                public void setReleaseNumber(int releaseNumber) {
                    this.releaseNumber = releaseNumber;
                }
            }
        }

        public static class SubjectsBean {
       
            private String id;
            private String title;
            private String detail;
            private String image;
            private String start_time;
            private String end_time;
            private int show_number;
            private String state;
            private int sort;
            private String descImage;
            private String template;
            private String url;
            private String wapUrl;
            private List<GoodsListBeanX> goodsList;
            private List<String> goodsIdsList;
            private List<GoodsRelationListBean> goodsRelationList;

            public String getId() {
                return id;
            }

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

            public String getTitle() {
                return title;
            }

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

            public String getDetail() {
                return detail;
            }

            public void setDetail(String detail) {
                this.detail = detail;
            }

            public String getImage() {
                return image;
            }

            public void setImage(String image) {
                this.image = image;
            }

            public String getStart_time() {
                return start_time;
            }

            public void setStart_time(String start_time) {
                this.start_time = start_time;
            }

            public String getEnd_time() {
                return end_time;
            }

            public void setEnd_time(String end_time) {
                this.end_time = end_time;
            }

            public int getShow_number() {
                return show_number;
            }

            public void setShow_number(int show_number) {
                this.show_number = show_number;
            }

            public String getState() {
                return state;
            }

            public void setState(String state) {
                this.state = state;
            }

            public int getSort() {
                return sort;
            }

            public void setSort(int sort) {
                this.sort = sort;
            }

            public String getDescImage() {
                return descImage;
            }

            public void setDescImage(String descImage) {
                this.descImage = descImage;
            }

            public String getTemplate() {
                return template;