一手遮天 Android - view(RecyclerView): RecyclerView 上拉加载更多数据

项目地址 https://github.com/webabcd/AndroidDemo
作者 webabcd

一手遮天 Android - view(RecyclerView): RecyclerView 上拉加载更多数据

示例如下:

/view/recyclerview/RecyclerViewDemo4.java

/**
 * 演示 RecyclerView 的上拉加载更多数据
 *
 * adapter 参见 RecyclerViewDemo4Adapter.java
 * scroll 监听器参见  RecyclerViewDemo4OnScrollListener.java
 */

package com.webabcd.androiddemo.view.recyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;

import com.webabcd.androiddemo.R;

import java.util.List;

public class RecyclerViewDemo4 extends AppCompatActivity {

    private RecyclerView _recyclerView;

    // 数据分页的页索引
    private int _pageIndex = 0;
    // 数据分页的页大小
    private int _pageSize = 20;
    // 是否正在加载数据
    private boolean _isLoading = false;

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

        _recyclerView = findViewById(R.id.recyclerView1);

        sample();
    }

    private void sample() {

        _recyclerView.setLayoutManager(new LinearLayoutManager(RecyclerViewDemo4.this));
        // 初始数据
        _recyclerView.setAdapter(new RecyclerViewDemo4Adapter(MyData.generateDataList(_pageIndex, _pageSize)));

        _recyclerView.addOnScrollListener(new RecyclerViewDemo4OnScrollListener() {
            @Override
            public void onBottom() {
                if (!_isLoading) {
                    // 加载更多数据
                    _pageIndex++;
                    _isLoading = true;
                    new MyTask().execute(_pageIndex, _pageSize);
                }
            }
        });
    }

    // 异步加载数据
    private class MyTask extends AsyncTask<Integer, Void, List<MyData>> {
        @Override
        protected List<MyData> doInBackground(Integer... params) {
            SystemClock.sleep(1000);

            int pageIndex = params[0];
            int pageSize = params[1];

            // 请求到更多数据
            return MyData.generateDataList(pageIndex * pageSize, pageSize);
        }

        @Override
        protected void onPostExecute(List<MyData> result) {
            RecyclerViewDemo4Adapter adapter = (RecyclerViewDemo4Adapter)_recyclerView.getAdapter();
            if (_pageIndex > 3) {
                // 没有更多数据了
                adapter.setHasMoreItems(false);
            } else {
                // 追加数据
                adapter.appendData(result);
            }

            adapter.notifyDataSetChanged();
            _isLoading = false;
        }
    }
}

\view\recyclerview\RecyclerViewDemo4Adapter.java

/**
 * 自定义 RecyclerView.Adapter
 */

package com.webabcd.androiddemo.view.recyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.webabcd.androiddemo.R;

import java.util.List;

public class RecyclerViewDemo4Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
    private List<MyData> _myDataList;

    // 是否还有更多数据可供加载
    private boolean _hasMoreItems = true;

    public RecyclerViewDemo4Adapter(List<MyData> myDataList) {
        _myDataList = myDataList;
    }

    // 追加数据
    public void appendData(List<MyData> myDataList) {
        _myDataList.addAll(myDataList);
    }

    // 告诉我是否还有更多数据可供加载
    public void setHasMoreItems(boolean hasMoreItems) {
        this._hasMoreItems = hasMoreItems;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == 0) {
            // 用于显示数据的 item
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_recyclerview_myrecyclerviewadapter_1, parent, false);
            return new ViewHolder(view);
        } else {
            // 用于显示“加载更多”的 item
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view_recyclerview_recyclerviewdemo8_loadmore, parent, false);
            return new LoadMoreViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {

        if (viewHolder instanceof ViewHolder) { // 用于显示数据的 item
            ViewHolder holder = (ViewHolder)viewHolder;
            MyData myData = _myDataList.get(position);
            holder.imgLogo.setImageResource(myData.getLogoId());
            holder.txtName.setText(myData.getName());
            holder.txtComment.setText(myData.getComment());
        } else if (viewHolder instanceof LoadMoreViewHolder) { // 用于显示“加载更多”的 item
            LoadMoreViewHolder holder = (LoadMoreViewHolder)viewHolder;
            if (!_hasMoreItems) { // 没有更多数据时
                holder.textView.setText("没有更多数据了");
                holder.progressBar.setVisibility(View.GONE);
            } else { // 请求更多数据时
                holder.textView.setText("正在加载");
                holder.progressBar.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public int getItemCount() {
        // + 1 是因为多了一个“加载更多”的 item
        return _myDataList.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (position < _myDataList.size()) {
            return 0; // 用于显示数据的 item
        } else {
            return 1; // 用于显示“加载更多”的 item
        }
    }


    // 用于显示数据的 item 的 ViewHolder
    class ViewHolder extends RecyclerView.ViewHolder {

        private View container;
        private ImageView imgLogo;
        private TextView txtName;
        private TextView txtComment;

        public ViewHolder (View view)  {
            super(view);

            container = view;
            imgLogo = view.findViewById(R.id.imgLogo);
            txtName = view.findViewById(R.id.txtName);
            txtComment = view.findViewById(R.id.txtComment);
        }
    }

    // 用于显示“加载更多”的 item 的 ViewHolder
    class LoadMoreViewHolder extends RecyclerView.ViewHolder {

        private View container;
        private ProgressBar progressBar;
        private TextView textView;

        public LoadMoreViewHolder(View view) {
            super(view);

            container = view;
            progressBar = view.findViewById(R.id.progressBar);
            textView = view.findViewById(R.id.textView);
        }
    }
}

\view\recyclerview\RecyclerViewDemo4OnScrollListener.java

/**
 * 自定义 RecyclerView.OnScrollListener
 */

package com.webabcd.androiddemo.view.recyclerview;

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

public abstract class RecyclerViewDemo4OnScrollListener extends RecyclerView.OnScrollListener {

    // 最近一次滑动是否是上滑
    private boolean isSlidingUpward = false;

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);

        LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
        // 当不滑动时
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            // 获取最后一个完全显示的 item 的 position
            int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
            int itemCount = manager.getItemCount();

            // 判断是否滑动到了最后一个 item 并且是上滑
            if (lastItemPosition == (itemCount - 1) && isSlidingUpward) {
                // 滚动到底了
                onBottom();
            }
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        // 大于 0 代表上滑
        isSlidingUpward = dy > 0;
    }

    /**
     * 滚动到底的回调
     */
    public abstract void onBottom();
}

/layout/activity_view_recyclerview_recyclerviewdemo4.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

</LinearLayout>

/layout/item_view_recyclerview_myrecyclerviewadapter_1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="64dp"
        android:layout_height="64dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1">

        <TextView
            android:id="@+id/txtName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#1D1D1D"
            android:textSize="24sp" />

        <TextView
            android:id="@+id/txtComment"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#B4B4B4"
            android:textSize="14sp" />

    </LinearLayout>

</LinearLayout>

/layout/item_view_recyclerview_recyclerviewdemo8_loadmore.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="64dp"
    android:gravity="center"
    android:orientation="horizontal">

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_gravity="center"
        android:layout_marginRight="10dp"
        android:indeterminateDrawable="@drawable/rotate_progressbar_indeterminate"
        android:indeterminateDuration="500"
        android:visibility="visible" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#999999" />

</LinearLayout>

项目地址 https://github.com/webabcd/AndroidDemo
作者 webabcd

posted @ 2021-06-02 08:29  webabcd  阅读(258)  评论(0编辑  收藏  举报