美文网首页
Android实现上拉加载、下拉刷新(RecyclerView+

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

作者: i宁静的鱼 | 来源:发表于2019-08-13 15:49 被阅读0次
    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

    相关文章

      网友评论

          本文标题:Android实现上拉加载、下拉刷新(RecyclerView+

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