自定义加载更多的Recycleview

Posted 和平world

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义加载更多的Recycleview相关的知识,希望对你有一定的参考价值。

自定义的加载更多的recycleView

<span style="font-size:18px;">public class LoadingRecyclerView extends RecyclerView {
    static final String TAG = "LoadingRecyclerView";

    private LoadingMoreListener mMoreListener;
    private static final int NONE = 0;//空闲状态
    private static final int LOADING = 1;//加载状态
    private static final int LOADING_ERROR = 2;//加载状态
    private static final int NO_MORE_DATA = 3;//没有更多数据
    private static final boolean DEBUG = false;
    private int mState = 0;//加载状态

    public LoadingRecyclerView(Context context) {
        super(context);
        init();
    }

    public LoadingRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LoadingRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_DRAGGING){
                    if (!isLoading() && canScroolLoadingMore() && mState == LOADING_ERROR){
                        reLoading();

                    }
                }
            }

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

                if (isLastPositionVisible() && !isLoading() && canScroolLoadingMore()) {
                    //翻到最后,并且当前状态不为加载中,加载
                    if (DEBUG) {
                        Log.e(TAG, "已翻到最后");
                    }
                   reLoading();
                }

            }
        });
    }


    /**
     * 是否可以加载更多
     *
     * @return
     */
    private boolean canScroolLoadingMore() {
        if (mState == LOADING_ERROR || mState == NO_MORE_DATA) {
            return false;
        }
        return true;
    }


    /**
     * 加载完成
     */
    public void onLoadingComplete() {
        mState = NONE;
    }


    /**
     * 加载失败
     *
     * @return
     */
    public void onLoadingError() {
        mState = LOADING_ERROR;
        getLoadingMoreAdapter().loadingError();
    }


    /**
     * 重新加载
     */
    public void reLoading() {
        if (!isLoading()) {
            if (mMoreListener != null) {
                mState = LOADING;
                getLoadingMoreAdapter().resetLoadingMore();
                if (mMoreListener != null)
                mMoreListener.onLoadingMore();
            }
        }
    }

    /**
     * 重置加载中布局
     */
    public void resetLoadingView() {
        getLoadingMoreAdapter().resetLoadingMore();
    }


    /**
     * 没有更多数据了
     *
     * @return
     */
    public void noMoreData() {
        getLoadingMoreAdapter().noMoreData();
    }


    public LoadingMoreAdapter getLoadingMoreAdapter() {
        return (LoadingMoreAdapter) getAdapter();
    }


    public LoadingMoreAdapter.LoadingMoreHolder getLoadingMoreHolder() {
        //得到要更新的item的view
        View view = getChildAt(getChildCount() - 1);
        if (null != getChildViewHolder(view)) {
            return (LoadingMoreAdapter.LoadingMoreHolder) getChildViewHolder(view);

        }
        return null;
    }

    public boolean isLastPositionVisible() {
        int itemCount = getAdapter().getItemCount();
        return itemCount == getLastVisiblePosition() + 1;
    }


    /**
     * 设置是否还有更多数据标记
     *
     * @param isNoMore
     */
    public void setNoMoreData(boolean isNoMore) {
        if (isNoMore) {
            mState = NO_MORE_DATA;
            noMoreData();
        } else {
            mState = NONE;
        }
    }

    /**
     * 是否加载中..
     *
     * @return
     */
    public boolean isLoading() {
        return mState == LOADING;
    }

    /**
     * 获取最后一条展示的位置
     *
     * @return
     */
    private int getLastVisiblePosition() {
        int position;
        if (getLayoutManager() instanceof LinearLayoutManager) {
            position = ((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition();
        } else if (getLayoutManager() instanceof GridLayoutManager) {
            position = ((GridLayoutManager) getLayoutManager()).findLastVisibleItemPosition();
        } else if (getLayoutManager() instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) getLayoutManager();
            int[] lastPositions = layoutManager.findLastVisibleItemPositions(new int[layoutManager.getSpanCount()]);
            position = getMaxPosition(lastPositions);
        } else {
            position = getLayoutManager().getItemCount() - 1;
        }

        if (DEBUG) {
            Log.e(TAG, position + "");
        }

        return position;
    }

    /**
     * 获得最大的位置
     *
     * @param positions
     * @return
     */
    private int getMaxPosition(int[] positions) {
        int size = positions.length;
        int maxPosition = Integer.MIN_VALUE;
        for (int i = 0; i < size; i++) {
            maxPosition = Math.max(maxPosition, positions[i]);
        }
        return maxPosition;
    }


    public void setLoadingMoreListener(LoadingMoreListener listener) {
        mMoreListener = listener;
    }


    public interface LoadingMoreListener {
        public void onLoadingMore();
    }


}</span>

加载更多的RecycleviewAdapter

<span style="font-size:24px;">public abstract class LoadingMoreAdapter<T> extends RecyclerView.Adapter {
    private List<T> list;
    public static final int ITEM = 0, LOADING_MORE = 1, NO_MORE_DATA = 2, LOADING_ERROR = 3;
    public int mState = LOADING_MORE;
    protected Context context;

    public LoadingMoreAdapter(Context context, List<T> list) {
        this.context = context;
        this.list = list;

    }

    @Override
    public int getItemViewType(int position) {
        if (position == list.size()) {
            return mState;
        }
        return ITEM;
    }

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

        switch (viewType) {
            case LOADING_MORE:
                //加载更多
                return new LoadingMoreHolder(LayoutInflater.from(context).inflate(R.layout.layout_loading_more, parent, false));
            case NO_MORE_DATA:
                //没有更多数据
                LoadingMoreHolder noMoreDataHolder = new LoadingMoreHolder(LayoutInflater.from(context).inflate(R.layout.layout_loading_more, parent, false));
                noMoreDataHolder.setText("没有更多数据了");
                noMoreDataHolder.visibleProgressBar(false);
                return noMoreDataHolder;
            case LOADING_ERROR:
                //加载错误
                LoadingMoreHolder errorHolder = new LoadingMoreHolder(LayoutInflater.from(context).inflate(R.layout.layout_loading_more, parent, false));
                errorHolder.setText("加载失败,点击重新加载");
                errorHolder.visibleProgressBar(false);
                return errorHolder;
            case ITEM:
                return getItemHolder();
        }
        return null;

    }


    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (position == list.size()) {
            //加载更多
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (holder.itemView.getParent() instanceof LoadingRecyclerView) {
                        if (mState == LOADING_ERROR) {
                            LoadingRecyclerView recyclerView = (LoadingRecyclerView) holder.itemView.getParent();
                            recyclerView.reLoading();
                        }
                    }
                }
            });
        } else {
            setItemHolder(holder, position);
        }
    }

    @Override
    public int getItemCount() {
        //+1表示加载更多布局
        return list == null ? 0 : list.size() + 1;
    }


    /**
     * 没有更多数据
     */
    public void noMoreData() {
        mState = NO_MORE_DATA;
        notifyDataSetChanged();
    }

    /**
     * 加载数据
     * @return
     */
    public void resetLoadingMore() {
        mState = LOADING_MORE;
        notifyDataSetChanged();
    }

    /**
     * 加载数据
     * @return
     */
    public void loadingError() {
        mState = LOADING_ERROR;
        notifyDataSetChanged();
    }


    public abstract RecyclerView.ViewHolder getItemHolder();

    public abstract void setItemHolder(RecyclerView.ViewHolder holder, int position);


    /**
     * 加载中布局
     */
    class LoadingMoreHolder extends RecyclerView.ViewHolder {
        TextView tv_text;
        ProgressBar progress_bar;

        public LoadingMoreHolder(View itemView) {
            super(itemView);
            tv_text = (TextView) itemView.findViewById(R.id.tv_text);
            progress_bar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
        }

        public void setText(String msg) {
            tv_text.setText(msg);
        }

        public void visibleProgressBar(boolean isVisible) {
            if (isVisible) {
                progress_bar.setVisibility(View.VISIBLE);
            } else {
                progress_bar.setVisibility(View.GONE);
            }
        }

    }

}</span>



以上是关于自定义加载更多的Recycleview的主要内容,如果未能解决你的问题,请参考以下文章

一句代码搞定 RecycleView 侧滑菜单添加头部底部加载更多

自己封装的工具类,使用原生SwipeRefreshLayout+RecycleView实现下拉刷新和加载更多

Android 使用RecycleView列表实现加载更多

java recycleview加载更多帮手

滚动时将更多数据加载到recycleview

Jetpack Compose 无限加载列表(滚到底部自动加载更多)