美文网首页
AndroidStudio自带的“SwipeRefreshLay

AndroidStudio自带的“SwipeRefreshLay

作者: 穿越平行宇宙 | 来源:发表于2019-07-07 15:39 被阅读0次

使用MVP 实现请求数据,Model 路径如下如所示:

image.png

首先使用MVP请求数据

1. 页面布局

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=".view.MainActivity">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

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

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


    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>

recycler_item.xml

<?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">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_margin="20dp"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/iv"
        android:layout_margin="10dp"
        android:layout_toRightOf="@id/iv"
        android:text="@string/app_name" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_time"
        android:layout_margin="10dp"
        android:layout_toRightOf="@id/iv"
        android:text="@string/app_name" />


</RelativeLayout>

2. bean包下的数据实体类

WealBean.java

public class WealBean {


    /**
     * error : false
     * results : [{"_id":"5c6a4ae99d212226776d3256","createdAt":"2019-02-18T06:04:25.571Z","desc":"2019-02-18","publishedAt":"2019-02-18T06:05:41.975Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1g0ajj4h6ndj30sg11xdmj.jpg","used":true,"who":"lijinshanmx"},{"_id":"5c6385b39d21225dd7a417ce","createdAt":"2019-02-13T02:49:23.946Z","desc":"2019-02-13","publishedAt":"2019-02-13T02:49:33.16Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1g04lsmmadlj31221vowz7.jpg","used":true,"who":"lijinshanmx"},{"_id":"5c4578db9d212264d4501d40","createdAt":"2019-01-21T07:46:35.304Z","desc":"2019-01-21","publishedAt":"2019-01-21T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqgy1fze94uew3jj30qo10cdka.jpg","used":true,"who":"lijinshanmx"},{"_id":"5c2dabdb9d21226e068debf9","createdAt":"2019-01-03T06:29:47.895Z","desc":"2019-01-03","publishedAt":"2019-01-03T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fytdr77urlj30sg10najf.jpg","used":true,"who":"lijinshanmx"},{"_id":"5c25db189d21221e8ada8664","createdAt":"2018-12-28T08:13:12.688Z","desc":"2018-12-28","publishedAt":"2018-12-28T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fymj13tnjmj30r60zf79k.jpg","used":true,"who":"lijinshanmx"},{"_id":"5c12216d9d21223f5a2baea2","createdAt":"2018-12-13T09:07:57.2Z","desc":"2018-12-13","publishedAt":"2018-12-13T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqgy1fy58bi1wlgj30sg10hguu.jpg","used":true,"who":"lijinshanmx"},{"_id":"5bfe1a5b9d2122309624cbb7","createdAt":"2018-11-28T04:32:27.338Z","desc":"2018-11-28","publishedAt":"2018-11-28T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqgy1fxno2dvxusj30sf10nqcm.jpg","used":true,"who":"lijinshanmx"},{"_id":"5bf22fd69d21223ddba8ca25","createdAt":"2018-11-19T03:36:54.950Z","desc":"2018-11-19","publishedAt":"2018-11-19T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqgy1fxd7vcz86nj30qo0ybqc1.jpg","used":true,"who":"lijinshanmx"},{"_id":"5be14edb9d21223dd50660f8","createdAt":"2018-11-06T08:20:43.656Z","desc":"2018-11-06","publishedAt":"2018-11-06T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqgy1fwyf0wr8hhj30ie0nhq6p.jpg","used":true,"who":"lijinshanmx"},{"_id":"5bcd71979d21220315c663fc","createdAt":"2018-10-22T06:43:35.440Z","desc":"2018-10-22","publishedAt":"2018-10-22T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqgy1fwgzx8n1syj30sg15h7ew.jpg","used":true,"who":"lijinshanmx"},{"_id":"5bc434ac9d212279160c4c9e","createdAt":"2018-10-15T06:33:16.497Z","desc":"2018-10-15","publishedAt":"2018-10-15T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fw8wzdua6rj30sg0yc7gp.jpg","used":true,"who":"lijinshanmx"},{"_id":"5bbb0de09d21226111b86f1c","createdAt":"2018-10-08T07:57:20.978Z","desc":"2018-10-08","publishedAt":"2018-10-08T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fw0vdlg6xcj30j60mzdk7.jpg","used":true,"who":"lijinshanmx"},{"_id":"5ba206ec9d2122610aba3440","createdAt":"2018-09-19T08:21:00.295Z","desc":"2018-09-19","publishedAt":"2018-09-19T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fvexaq313uj30qo0wldr4.jpg","used":true,"who":"lijinshanmx"},{"_id":"5b9771a29d212206c1b383d0","createdAt":"2018-09-11T07:41:22.491Z","desc":"2018-09-11","publishedAt":"2018-09-11T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fv5n6daacqj30sg10f1dw.jpg","used":true,"who":"lijinshanmx"},{"_id":"5b830bba9d2122031f86ee51","createdAt":"2018-08-27T04:21:14.703Z","desc":"2018-08-27","publishedAt":"2018-08-28T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fuo54a6p0uj30sg0zdqnf.jpg","used":true,"who":"lijinshanmx"},{"_id":"5b7b836c9d212201e982de6e","createdAt":"2018-08-21T11:13:48.989Z","desc":"2018-08-21","publishedAt":"2018-08-21T00:00:00.0Z","source":"web","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fuh5fsvlqcj30sg10onjk.jpg","used":true,"who":"lijinshanmx"},{"_id":"5b74e9409d21222c52ae4cb4","createdAt":"2018-08-16T11:02:24.289Z","desc":"2018-08-16","publishedAt":"2018-08-16T00:00:00.0Z","source":"api","type":"福利","url":"https://ws1.sinaimg.cn/large/0065oQSqly1fubd0blrbuj30ia0qp0yi.jpg","used":true,"who":"lijinshan"},{"_id":"5b7102749d2122341d563844","createdAt":"2018-08-13T12:00:52.458Z","desc":"2018-08-13","publishedAt":"2018-08-13T00:00:00.0Z","source":"api","type":"福利","url":"https://ww1.sinaimg.cn/large/0065oQSqly1fu7xueh1gbj30hs0uwtgb.jpg","used":true,"who":"lijinshan"},{"_id":"5b6bad449d21226f45755582","createdAt":"2018-08-09T10:56:04.962Z","desc":"2018-08-09","publishedAt":"2018-08-09T00:00:00.0Z","source":"web","type":"福利","url":"https://ww1.sinaimg.cn/large/0065oQSqgy1fu39hosiwoj30j60qyq96.jpg","used":true,"who":"lijinshanmx"},{"_id":"5b67b7fd9d2122195bdbd806","createdAt":"2018-08-06T10:52:45.809Z","desc":"2018-08-06","publishedAt":"2018-08-06T00:00:00.0Z","source":"api","type":"福利","url":"https://ww1.sinaimg.cn/large/0065oQSqly1ftzsj15hgvj30sg15hkbw.jpg","used":true,"who":"lijinshan"}]
     */

    private boolean error;
    private List<ResultsBean> results;

    public boolean isError() {
        return error;
    }

    public void setError(boolean error) {
        this.error = error;
    }

    public List<ResultsBean> getResults() {
        return results;
    }

    public void setResults(List<ResultsBean> results) {
        this.results = results;
    }

    public static class ResultsBean {
        /**
         * _id : 5c6a4ae99d212226776d3256
         * createdAt : 2019-02-18T06:04:25.571Z
         * desc : 2019-02-18
         * publishedAt : 2019-02-18T06:05:41.975Z
         * source : web
         * type : 福利
         * url : https://ws1.sinaimg.cn/large/0065oQSqly1g0ajj4h6ndj30sg11xdmj.jpg
         * used : true
         * who : lijinshanmx
         */

        private String _id;
        private String createdAt;
        private String desc;
        private String publishedAt;
        private String source;
        private String type;
        private String url;
        private boolean used;
        private String who;

        public String get_id() {
            return _id;
        }

        public void set_id(String _id) {
            this._id = _id;
        }

        public String getCreatedAt() {
            return createdAt;
        }

        public void setCreatedAt(String createdAt) {
            this.createdAt = createdAt;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

        public String getPublishedAt() {
            return publishedAt;
        }

        public void setPublishedAt(String publishedAt) {
            this.publishedAt = publishedAt;
        }

        public String getSource() {
            return source;
        }

        public void setSource(String source) {
            this.source = source;
        }

        public String getType() {
            return type;
        }

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

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public boolean isUsed() {
            return used;
        }

        public void setUsed(boolean used) {
            this.used = used;
        }

        public String getWho() {
            return who;
        }

        public void setWho(String who) {
            this.who = who;
        }
    }
}

3. api 包下的(请求数据接口的封装)

RequestInterface.java

public interface RequestInterface {

    // http://gank.io/api/data/福利/20/1

    String wealUrl = "http://gank.io/api/data/福利/20/";

    @GET
    Observable<WealBean> setData(@Url String page);

}

RequestManager.java

public class RequestManager {

    private static RequestManager mRequestManager;
    private static Retrofit retrofit;

    private RequestManager() {
        initInterface();
    }


    // 初始化Retrofit 的对象
    private void initInterface() {

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .writeTimeout(5000, TimeUnit.MILLISECONDS)
                .build();

        retrofit = new Retrofit.Builder()
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(RequestInterface.wealUrl)
                .build();

    }


    // 使用单例模式(懒汉式)构建当前类的对象
    public static RequestManager getManager() {
        if (mRequestManager == null) {
            synchronized (RequestManager.class) {
                if (mRequestManager == null) {
                    mRequestManager = new RequestManager();
                }
            }
        }
        return mRequestManager;
    }


    public RequestInterface getRetrofit() {
        return retrofit.create(RequestInterface.class);
    }


}

4.model 包下的 (model 接口与实现)

WealModel.java

public interface WealModel {

    void initData(String page, CallBack callBack);

    interface CallBack {

        void onSuccess(WealBean bean);

        void onFail(String message);

    }
    
}

WealModelIpi.java

public class WealModelIpi implements WealModel {

    @Override
    public void initData(String page, final CallBack callBack) {

        RequestManager.getManager().getRetrofit()
                .setData(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WealBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(WealBean value) {
                        if (value != null && value.getResults() != null && value.getResults().size() > 0) {
                            callBack.onSuccess(value);
                        } else {
                            callBack.onFail("解析失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        callBack.onFail(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

}

5.view 包下的(view 接口)

WealView.java

public interface WealView {

    void onSuccess(WealBean bean);

    void onFail(String message);

}

6.presenter 包下的(presenter 接口与实现)

WealPresenter.java

public interface WealPresenter {

    void getData(String page);

}

WealPresenterIpi.java

public class WealPresenterIpi implements WealPresenter {

    private WealView mWealView;
    private WealModel mWealModel;


    public WealPresenterIpi(WealView wealView) {
        mWealView = wealView;
        mWealModel = new WealModelIpi();
    }

    @Override
    public void getData(String page) {
        if (mWealModel != null) {
            mWealModel.initData(page, new WealModel.CallBack() {
                @Override
                public void onSuccess(WealBean bean) {
                    if (mWealView != null) {
                        mWealView.onSuccess(bean);
                    }
                }

                @Override
                public void onFail(String message) {
                    if (mWealView != null) {
                        mWealView.onFail(message);
                    }
                }
            });
        }
    }

}

7.UI页面的修改

MainActivity.java

public class MainActivity extends AppCompatActivity implements WealView, SwipeRefreshLayout.OnRefreshListener {

    private RecyclerView mRlv;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private List<WealBean.ResultsBean> mList;
    private int page = 1;
    private HomeAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initData() {

        WealPresenterIpi wealPresenterIpi = new WealPresenterIpi(this);
        wealPresenterIpi.getData(page + "");

    }

    @Override
    public void onSuccess(WealBean bean) {

        if (page == 1) {
            mList.clear();
            Toast.makeText(this, "刷新成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "加载成功", Toast.LENGTH_SHORT).show();
        }

        List<WealBean.ResultsBean> results = bean.getResults();

        mList.addAll(results);
        mAdapter.setData(mList);
        mAdapter.notifyDataSetChanged();

        // 设置刷新结束
        mSwipeRefreshLayout.setRefreshing(false);

    }

    @Override
    public void onFail(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void initView() {
        // 获取控件对象
        mRlv = (RecyclerView) findViewById(R.id.rlv);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        // 设置数据源
        mList = new ArrayList<>();

        // 设置显示方式
        mRlv.setLayoutManager(new LinearLayoutManager(this));

        // 设置适配器
        mAdapter = new HomeAdapter(this, mList);
        mRlv.setAdapter(mAdapter);

        // 加载更多
        initLoading();

        // 下拉刷新
        mSwipeRefreshLayout.setOnRefreshListener(this);

    }

    private void initLoading() {

        // 上拉加载更多
        mRlv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                // 判断是否到达底部
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {

                    // 获取布局管理器对象
                    RecyclerView.LayoutManager layoutManager = mRlv.getLayoutManager();
                    if (layoutManager instanceof LinearLayoutManager) {

                        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;

                        // 找到最后一个可见的条目
                        int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();

                        // 获取数据的总数量
                        int itemCount = recyclerView.getAdapter().getItemCount();

                        if (lastVisibleItemPosition == itemCount - 1) {
                            // 加载数据
                            page++;
                            initData();
                        }


                    }


                }


            }
        });

    }

    @Override
    public void onRefresh() {
        page = 1;
        initData();
    }
}

HomeAdapter.java

public class MainActivity extends AppCompatActivity implements WealView, SwipeRefreshLayout.OnRefreshListener {

    private RecyclerView mRlv;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private List<WealBean.ResultsBean> mList;
    private int page = 1;
    private HomeAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initData() {

        WealPresenterIpi wealPresenterIpi = new WealPresenterIpi(this);
        wealPresenterIpi.getData(page + "");

    }

    @Override
    public void onSuccess(WealBean bean) {

        if (page == 1) {
            mList.clear();
            Toast.makeText(this, "刷新成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "加载成功", Toast.LENGTH_SHORT).show();
        }

        List<WealBean.ResultsBean> results = bean.getResults();

        mList.addAll(results);
        mAdapter.setData(mList);
        mAdapter.notifyDataSetChanged();

        // 设置刷新结束
        mSwipeRefreshLayout.setRefreshing(false);

    }

    @Override
    public void onFail(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void initView() {
        // 获取控件对象
        mRlv = (RecyclerView) findViewById(R.id.rlv);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        // 设置数据源
        mList = new ArrayList<>();

        // 设置显示方式
        mRlv.setLayoutManager(new LinearLayoutManager(this));

        // 设置适配器
        mAdapter = new HomeAdapter(this, mList);
        mRlv.setAdapter(mAdapter);

        // 加载更多
        initLoading();

        // 下拉刷新
        mSwipeRefreshLayout.setOnRefreshListener(this);

    }

    private void initLoading() {

        // 上拉加载更多
        mRlv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                // 判断是否到达底部
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {

                    // 获取布局管理器对象
                    RecyclerView.LayoutManager layoutManager = mRlv.getLayoutManager();
                    if (layoutManager instanceof LinearLayoutManager) {

                        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;

                        // 找到最后一个可见的条目
                        int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();

                        // 获取数据的总数量
                        int itemCount = recyclerView.getAdapter().getItemCount();

                        if (lastVisibleItemPosition == itemCount - 1) {
                            // 加载数据
                            page++;
                            initData();
                        }


                    }


                }


            }
        });

    }

    @Override
    public void onRefresh() {
        page = 1;
        initData();
    }
}

效果图如下:

SwipeRefreshLayout使用.gif

相关文章

网友评论

      本文标题:AndroidStudio自带的“SwipeRefreshLay

      本文链接:https://www.haomeiwen.com/subject/rqhbhctx.html