1. 程式人生 > >MVP模式 + RecyclerView瀑布流 + 上拉載入、下拉重新整理

MVP模式 + RecyclerView瀑布流 + 上拉載入、下拉重新整理

首先匯入一些用到的依賴:(不要忘記新增網路許可權)

//  包括OKhttp網路請求、springview重新整理載入、butterknife相當於findviewbyid、glide載入圖片

//  recyclerview-flexibledivider分割線

compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.liaoinstan.springview:library:1.3.0'
compile 'com.jakewharton:butterknife:8.8.1'
compile 'com.google.code.gson:gson:2.8.1'
compile 'com.yqritc:recyclerview-flexibledivider:1.4.0'
compile 'com.github.bumptech.glide:glide:4.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'
直接匯入依賴會報錯,這時候需要在最外部的Gradle的allprojects中匯入:
maven { url 'https://maven.google.com' }
MVP模式:
activity_main.xml
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.bwie.mvprecyclerviewlogin.MainActivity">

    <com.liaoinstan.springview.widget.SpringView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/springview">

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

    </com.liaoinstan.springview.widget.SpringView>

</LinearLayout>
adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">
    
    <ImageView
        android:scaleType="centerCrop"
        android:id="@+id/adapter_imageview"
        android:layout_width="wrap_content"
        android:layout_height="100dp" />

</LinearLayout>
mainActivity
public class MainActivity extends AppCompatActivity implements RecyclerViewListener{
    @BindView(R.id.recycleview)
    RecyclerView recycleview;
    @BindView(R.id.springview)
    SpringView springview;
    private RecyclerViewPresenter presenter;
    private IAdapter adapter;
    private StaggeredGridLayoutManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //  設定頭腳佈局的重新整理樣式
        springview.setHeader(new MeituanHeader(this));
        springview.setFooter(new MeituanFooter(this));
        //  得到控制元件,設定recyclerview的顯示樣式,為介面卡賦值
        presenter = new RecyclerViewPresenter(this);
        manager = new StaggeredGridLayoutManager(3, LinearLayout.VERTICAL);
        recycleview.setLayoutManager(manager);
        adapter = new IAdapter(this);
        recycleview.setAdapter(adapter);

        HorizontalDividerItemDecoration horizontalDividerItemDecoration =  new HorizontalDividerItemDecoration.Builder(this)
                .color(Color.RED)
//                .sizeResId(R.dimen.divider)
//                .marginResId(R.dimen.leftmargin, R.dimen.rightmargin)
                .build() ;
        //分割線
        recycleview.addItemDecoration(horizontalDividerItemDecoration);

        presenter.getData(true);

        springview.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                presenter.getData(true);
            }

            @Override
            public void onLoadmore() {
                presenter.getData(true);
            }
        });
    }

    @Override
    public void callBackSuccess(final Bean bean) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.setData(bean);
                springview.onFinishFreshAndLoad();
            }
        });
    }

    @Override
    public void callBackFailure(int code) {

    }
}
IAdapter
public class IAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private List<Bean.ListBean> list ;
    private int itemWidth ;

    public IAdapter(Context context) {
        this.context = context;
        Point point =  Utils.getDisplayInfomation(context);
        itemWidth = point.x / 3 ;

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.adapter, parent, false);
        IViewHolder viewHolder = new IViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(holder instanceof IViewHolder){
            IViewHolder iViewHolder = (IViewHolder)holder;
            //        float scale =  (float) itemWidth / (float) list.get(position).getPicWidth()  ;
            //        params.width = itemWidth;
            //        params.height = (int)( (float)scale * (float)list.get(position).getPicHeight()) ;

            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) iViewHolder.adapterImageview.getLayoutParams() ;
            params.width = itemWidth ;
            int height =  new Random().nextInt(1000);
            params.height =  height < 300 ? 300 : height ;

            iViewHolder.adapterImageview.setLayoutParams(params);
            //  請求網路圖片
            Glide.with(context).load(list.get(position).getPic()).into(iViewHolder.adapterImageview);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }
    //  資料
    public void setData(Bean bean){
        if(this.list == null){
            this.list = new ArrayList<>();
        }
        this.list.addAll(bean.getList());
        notifyDataSetChanged();
    }

    static class IViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.adapter_imageview)
        ImageView adapterImageview;
        IViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}
Bean
public class Bean {


    /**
     * ret_code : 200
     * ret_msg : ok
     * list : [{"date":"111","id":1,"pic":"http://p1.pstatp.com/large/22c90001cf8b5388ce33","title":" \n他\u201c祕書圈\u201d的人數規模,趕上了周永康","type":1},{"date":"333","id":3,"pic":"http://p1.pstatp.com/list/190x124/e580016ab3624f1ed33","title":"家裡的一分硬幣現在值多少錢?\n家裡的一分硬幣現在值多少錢?\n家裡的一分硬幣現在值多少錢?\n家裡的一分硬幣現在值多少錢?\n家裡的一分硬幣現在值多少錢","type":1},{"date":"444","id":4,"pic":"http://p1.pstatp.com/origin/26ec0004cc0249b49e7c","title":"世界上\u201c最恐怖\u201d的景點大盤點,中國竟然排在第一!","type":1},{"date":"6666","id":6,"pic":"http://p3.pstatp.com/list/190x124/216d001357929b02f476","title":" \n張愛朋首迴應白百何緋聞事件,短短二句話,白百何後悔看錯了吧!","type":1},{"date":"8888","id":8,"pic":"http://p1.pstatp.com/list/190x124/191a00048757f6714455","title":"中國又開工這一重大工程:連美國都造不出來 周邊國家沉默不語","type":1},{"date":"99","id":9,"pic":"http://p3.pstatp.com/list/190x124/22c700036549c9b5ff07","title":"中國第一黑老大東北王喬四爺 最終也逃不過法網恢恢","type":1},{"date":"111","id":10,"pic":"http://p3.pstatp.com/list/190x124/22c6000628d79850e6d7","title":"號稱中國關係最硬的人,奶奶是慈禧,大伯是光緒,哥哥是宣統!","type":1},{"date":"222","id":11,"pic":"http://p3.pstatp.com/list/190x124/22ca00011911b0a8061c","title":" \n\u201c二婚女和剩女,我該娶哪個啊?求救!\u201d","type":1},{"date":"2","id":18,"pic":"http://e.hiphotos.baidu.com/image/pic/item/bd315c6034a85edf392d2be340540923dc547549.jpg","title":"永創佳樂 專業蔬菜大棚/花卉大棚","type":1},{"date":"3","id":19,"pic":"http://c.hiphotos.baidu.com/image/pic/item/d000baa1cd11728ba5e562e2c1fcc3cec2fd2c22.jpg","title":"永創佳樂 專業蔬菜大棚/花卉大棚","type":1},{"date":"4","id":20,"pic":"http://e.hiphotos.baidu.com/image/pic/item/94cad1c8a786c91773f6c1f9c03d70cf3ac7577c.jpg","title":"永創佳樂 專業蔬菜大棚/花卉大棚","type":1},{"date":"5","id":21,"pic":"http://b.hiphotos.baidu.com/image/pic/item/32fa828ba61ea8d39c5a09c49e0a304e241f58f1.jpg","title":"中國又開工這一重大工程:連美國都造不出來 周邊國家沉默不語","type":1},{"date":"6","id":22,"pic":"http://a.hiphotos.baidu.com/image/pic/item/359b033b5bb5c9ea1dc17023dc39b6003af3b33b.jpg","title":"中國又開工這一重大工程:連美國都造不出來 周邊國家沉默不語","type":1},{"date":"7","id":23,"pic":"http://d.hiphotos.baidu.com/image/pic/item/38dbb6fd5266d0169a58eae99e2bd40734fa35a9.jpg","title":"中國又開工這一重大工程:連美國都造不出來 周邊國家沉默不語","type":1},{"date":"8","id":24,"pic":"http://h.hiphotos.baidu.com/image/pic/item/5bafa40f4bfbfbed34f348bf71f0f736aec31f43.jpg","title":"中國又開工這一重大工程:連美國都造不出來 周邊國家沉默不語","type":1},{"date":"9","id":25,"pic":"http://imgsrc.baidu.com/imgad/pic/item/9e3df8dcd100baa1706f8e964c10b912c8fc2e58.jpg","title":"中國又開工這一重大工程:連美國都造不出來 周邊國家沉默不語","type":1}]
     */

    private int ret_code;
    private String ret_msg;
    private List<ListBean> list;

    public int getRet_code() {
        return ret_code;
    }

    public void setRet_code(int ret_code) {
        this.ret_code = ret_code;
    }

    public String getRet_msg() {
        return ret_msg;
    }

    public void setRet_msg(String ret_msg) {
        this.ret_msg = ret_msg;
    }

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

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

    public static class ListBean {
        /**
         * date : 111
         * id : 1
         * pic : http://p1.pstatp.com/large/22c90001cf8b5388ce33
         * title :
         他“祕書圈”的人數規模,趕上了周永康
         * type : 1
         */

        private String date;
        private int id;
        private String pic;
        private String title;
        private int type;

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            this.date = date;
        }

        public int getId() {
            return id;
        }

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

        public String getPic() {
            return pic;
        }

        public void setPic(String pic) {
            this.pic = pic;
        }

        public String getTitle() {
            return title;
        }

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

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }
    }
}


View層
RecyclerViewListener(介面)
public interface RecyclerViewListener {
    public void callBackSuccess(Bean bean);
    public void callBackFailure(int code);
}
Presenter層
RecyclerViewPresenter
public class RecyclerViewPresenter {

    private RecyclerViewModel recyclerViewModel;
    private RecyclerViewListener listener;
    public RecyclerViewPresenter(RecyclerViewListener listener){
        this.listener = listener;
        this.recyclerViewModel = new RecyclerViewModel();
    }
    public void  getData(boolean up){
        recyclerViewModel.getData(up, new RecyclerViewModelListener() {
            @Override
            public void callbackSuccess(Bean bean) {
                listener.callBackSuccess(bean);
            }
            @Override
            public void callbackFalied(int code) {
                listener.callBackFailure(code);
            }
        });
    }
}
model層
RecyclerViewModel
public class RecyclerViewModel {
    //  從網路獲取資料
    public void getData(boolean up, final RecyclerViewModelListener listener){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://qhb.2dyt.com/Bwei/news?type=9&postkey=109rff1d1AK")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //  1 網路
                listener.callbackFalied(1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Gson gson = new Gson();
                Bean bean = gson.fromJson(result,Bean.class);
                listener.callbackSuccess(bean);
            }
        });
    }

}
RecyclerViewModelListener
public interface RecyclerViewModelListener {
    public void callbackSuccess(Bean bean);
    public void callbackFalied(int code);
}

utils工具類
public class Utils {

    /**
     * 獲取裝置螢幕尺寸
     * @param context
     * @return
     */
    public static Point getDisplayInfomation(Context context){
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return new Point(dm.widthPixels,dm.heightPixels);
    }

}