Android实现上拉加载、下拉刷新(RecyclerView+OkHttp)

  1. 在app目录下的build.gradle中添加所需依赖
    implementation 'com.github.mamumu:mmDialog:1.3.0'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'com.squareup.okhttp3:okhttp:4.0.1'
    implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.0-andx-16'
    implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.1.0-andx-16'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
  1. 创建RecyclerView的布局文件activity_pager.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">

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/refreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.scwang.smartrefresh.layout.header.ClassicsHeader
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <com.scwang.smartrefresh.layout.footer.ClassicsFooter
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </com.scwang.smartrefresh.layout.SmartRefreshLayout>

</RelativeLayout>
  1. 创建单条item的布局文件activity_pager_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"
    android:paddingTop="5dp">

    <TextView
        android:id="@+id/coursename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_marginStart="110dp"
        android:ellipsize="end"
        android:singleLine="true" />
    <TextView
        android:id="@+id/teachername"
        android:layout_below="@id/coursename"
        android:textSize="16sp"
        android:layout_marginStart="110dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true" />
    <TextView
        android:id="@+id/studentnum"
        android:textSize="16sp"
        android:layout_below="@id/teachername"
        android:layout_marginStart="110dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true" />

    <ImageView
        android:id="@+id/courselogo"
        android:layout_width="100dp"
        android:layout_height="65dp"
        android:layout_marginStart="5dp"
        android:scaleType="centerCrop"
        android:contentDescription="@string/app_name" />

    <View
        android:layout_below="@id/courselogo"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:background="@color/colorPrimary"/>

</RelativeLayout>
  1. 创建activity类PagerActivity
package com.iefeel.yudemo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iefeel.tools.YuPagerAdapter;
import com.mumu.dialog.MMAlertDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;

public class PagerActivity extends BaseActivity {

    private YuPagerAdapter madapter;
    private RecyclerView recyclerv;
    RefreshLayout refreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pager);

        refreshLayout = findViewById(R.id.refreshLayout);

        recyclerv = findViewById(R.id.recycler_view);
        LinearLayoutManager layomanager = new LinearLayoutManager(PagerActivity.this);
        recyclerv.setLayoutManager(layomanager);
        madapter = new YuPagerAdapter(PagerActivity.this);
        recyclerv.setAdapter(madapter);
        madapter.setOnItemClickListener(new YuPagerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int Position) {
                String s = madapter.demoData.get(Position).toString();
                MMAlertDialog.showDialog(PagerActivity.this,
                        "这是第"+ (Position+1) +"个item",
                        s,
                        null,
                        "确定",
                        false,
                        null,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(PagerActivity.this, "确定", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();
                            }
                        });
            }
        });

        setPullRefresher();

    }

    private void setPullRefresher(){
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                madapter.refresh();
                refreshlayout.finishRefresh(2000/*,false*/);
                //不传时间则立即停止刷新,传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                madapter.addmore();
                refreshlayout.finishLoadMore(2000/*,false*/);
                //不传时间则立即停止刷新,传入false表示加载失败
            }
        });
    }
    
}
  1. 创建RecyclerView的适配器YuPagerAdapter
package com.iefeel.tools;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.iefeel.yudemo.Config;
import com.iefeel.yudemo.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class YuPagerAdapter extends RecyclerView.Adapter<YuPagerAdapter.YuViewHolder> {

    //当前上下文对象
    Context context;
    //RecyclerView填充Item数据的List对象
    public ArrayList<HashMap<String, Object>> demoData = new ArrayList<>();
    private YuViewHolder holder;

    RemoteImageHelper imghelper = new RemoteImageHelper();

    public Yupager demoPager = new Yupager();

    private String TAG = "YuPagerAdapter";

    //定义每一页获取到的数据
    ArrayList<HashMap<String, Object>> pageList = new ArrayList<>();

    JSONObject demoJson = new JSONObject();
    JSONArray demoJarr = new JSONArray();

    private String rescode = "";
    private String resmesg = "";

    private MyHandler myHandler = new MyHandler();
    
    private String xdomain = "http://xuexi.iefeel.com";
    private String apikey = "3bc837e2a1b701871aac65bfa0c9ebf1";

    public YuPagerAdapter(Context context){
        this.context = context;
        this.addmore();
    }

    //创建ViewHolder
    @NonNull
    @Override
    public YuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //实例化得到Item布局文件的View对象
        View v = View.inflate(context, R.layout.activity_pager_item, null);
        //返回YuViewHolder的对象
        return new YuViewHolder(v);
    }

    private OnItemClickListener mItemClickListener;
    //item的回调接口
    public interface OnItemClickListener {
        void onItemClick(View view, int Position);
    }
    //定义一个设置点击监听器的方法
    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.mItemClickListener = itemClickListener;
    }

    //绑定数据
    @Override
    public void onBindViewHolder(@NonNull YuViewHolder holder, int position) {
        holder.coursename.setText(demoData.get(position).get("coursename").toString());
        holder.teachername.setText(demoData.get(position).get("teachername").toString());
        holder.studentnum.setText(demoData.get(position).get("studentnum").toString());
        imghelper.loadImage(holder.courselogo, demoData.get(position).get("courselogo").toString());
        //如果设置了回调,则设置点击事件
        if (mItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemClickListener.onItemClick(holder.itemView, position);
                }
            });
        }
    }

    //返回Item的数量
    @Override
    public int getItemCount() {
        return demoData.size();
    }

    //继承RecyclerView.ViewHolder抽象类的自定义ViewHolder
    class YuViewHolder extends RecyclerView.ViewHolder{
        TextView coursename;
        TextView teachername;
        TextView studentnum;
        ImageView courselogo;

        public YuViewHolder(View itemView) {
            super(itemView);
            coursename = itemView.findViewById(R.id.coursename);
            teachername = itemView.findViewById(R.id.teachername);
            studentnum = itemView.findViewById(R.id.studentnum);
            courselogo = itemView.findViewById(R.id.courselogo);
        }
    }

    //页面加载时调用
    public void addmore() {
        //增加数据
        demoPager.curpage ++;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("pagesize", Integer.toString(demoPager.pagesize))
                .add("curpage", Integer.toString(demoPager.curpage))
                .build();
        Request request = new Request.Builder()
                .url(xdomain + "/ydapi/coursecenter/index?apikey=" + apikey)
                .post(requestBody)
                .build();
        //异步请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = myHandler.obtainMessage();
                message.what = 1;
                message.obj = response.body().string();
                myHandler.sendMessage(message);
            }
        });
    }

    //页面刷新时调用
    public void refresh() {
        //刷新数据
        demoPager.curpage = 1;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("pagesize", Integer.toString(demoPager.pagesize))
                .add("curpage", Integer.toString(demoPager.curpage))
                .build();
        Request request = new Request.Builder()
                .url(xdomain + "/ydapi/coursecenter/index?apikey=" + apikey)
                .post(requestBody)
                .build();
        //异步请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = myHandler.obtainMessage();
                message.what = 2;
                message.obj = response.body().string();
                myHandler.sendMessage(message);
            }
        });
    }

    //使用Handler,将数据在主线程返回
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {//在这里进行UI界面的更新,这个方法是运行在UI主线程中的
            pageList.clear();
            pageList = new ArrayList<>();
            try {
                demoJson = new JSONObject((String) msg.obj);
                rescode = demoJson.getString("code");
                resmesg = demoJson.getString("msg");
                if(rescode.equals("success")){
                    demoJarr = demoJson.getJSONArray("data");
                    for(int i=0;i<demoJarr.length();i++){
                        HashMap<String,Object> map = new HashMap<>();
                        JSONObject onecourse = demoJarr.getJSONObject(i);
                        map.put("courseid", onecourse.getInt("id"));
                        map.put("coursename", onecourse.getString("name"));
                        map.put("teachername", "主讲:" + onecourse.getString("leadername"));
                        map.put("studentnum", "学员:" + onecourse.getString("studentnum"));
                        map.put("courselogo", onecourse.getString("logo"));
                        pageList.add(map);
                    }
                    JSONObject onepager = demoJson.getJSONObject("pager");
                    demoPager.allsize = onepager.getInt("allsize");
                    demoPager.allpage = onepager.getInt("allpage");
                    if(msg.what==1){
                        int position = demoData.size();
                        demoData.addAll(position, pageList);
                        notifyItemInserted(position);
                    }else if(msg.what==2){
                        demoData.clear();
                        demoData = new ArrayList<>();
                        demoData.addAll(pageList);
                        notifyDataSetChanged();
                    }
                }else{
                    Log.e(TAG, resmesg);
                }
            }catch (JSONException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

}
  1. 分页辅助类YuPager
package com.iefeel.tools;

public class Yupager {

    public int allsize = 0; //总共条数
    public int pagesize = 10; //每页条数
    public int allpage = 0; //总共页数
    public int curpage = 0; //当前页数

}
  1. 获取网络图片辅助类RemoteImageHelper
package com.iefeel.tools;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.iefeel.yudemo.R;

public class RemoteImageHelper {

    private final Map<String, Drawable> cache = new HashMap<String, Drawable>();

    public void loadImage(final ImageView imageView, final String urlString) {
        loadImage(imageView, urlString, true);
    }

    public void loadImage(final ImageView imageView, final String urlString, boolean useCache) {
        if (useCache && cache.containsKey(urlString)) {
            imageView.setImageDrawable(cache.get(urlString));
        }

        //You may want to show a "Loading" image here
        imageView.setImageResource(R.drawable.ic_launcher);

        //Log.d(this.getClass().getSimpleName(), "Image url:" + urlString);

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                imageView.setImageDrawable((Drawable) message.obj);
            }
        };

        Runnable runnable = new Runnable() {
            public void run() {
                Drawable drawable = null;
                try {
                    InputStream is = download(urlString);
                    drawable = Drawable.createFromStream(is, "src");

                    if (drawable != null) {
                        cache.put(urlString, drawable);
                    }
                } catch (Exception e) {
                    Log.e(this.getClass().getSimpleName(), "Image download failed", e);
                    //Show "download fail" image
                    drawable = imageView.getResources().getDrawable(R.drawable.ic_launcher);
                }

                //Notify UI thread to show this image using Handler
                Message msg = handler.obtainMessage(1, drawable);
                handler.sendMessage(msg);
            }
        };
        new Thread(runnable).start();

    }

    /**
     * Download image from given url.
     * Make sure you have "android.permission.INTERNET" permission set in AndroidManifest.xml.
     *
     * @param urlString
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    private InputStream download(String urlString) throws MalformedURLException, IOException {
        InputStream inputStream = (InputStream) new URL(urlString).getContent();
        return inputStream;
    }
}
  1. 运行效果图


    上拉加载.jpg

    下拉刷新.jpg
  2. item点击事件


    item点击事件.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342