android中如何实现上拉加载更多功能(建议收藏)

Posted kaolagirl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android中如何实现上拉加载更多功能(建议收藏)相关的知识,希望对你有一定的参考价值。

上拉加载更多功能实际上就是给RecyclerView增加一个FooterView,然后通过判断是否滑动到了最后一条Item,来控制FooterView的显示和隐藏,接下来我们来看下如何实现:

一.给Adapter添加FootView
  1. 首先定义了布局和数据加载状态的一些标志
  2. 在getItemViewType方法中设置最后一个Item为FooterView
  3. 在onCreateViewHolder方法中根据viewType来加载不同的布局
  4. 最后在onBindViewHolder方法中设置一下加载的状态显示就OK了

注意:由于多了一个FooterView,所以要记得在getItemCount方法的返回值中加上1

public class GoodSearchAdpter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<Map<String, Object>> list = new ArrayList<>();
    private Context context;
    //普通布局
    private final int TYPE_ITEM = 1;
    //脚布局
    private final int TYPE_FOOTER = 2;
    //当前加载状态,默认为加载完成
    private int loadState ;
    // 正在加载
    public final int LOADING = 1;
    // 加载完成
    public final int LOADING_COMPLETE = 2;
    // 加载到底
    public final int LOADING_END = 3;

    public List<Map<String, Object>> getData() {
        return list;
    }

    public void setData(List<Map<String, Object>> list) {
        this.list= list;
    }

//    public GoodSearchAdpter(List<Map<String, Object>> list, Context context) {
//        this.list = list;
//        this.context = context;
//    }

    public GoodSearchAdpter(Context context) {
        this.context = context;
    }

    @Override
    public int getItemViewType(int position) {
        //给最后一个item设置foot_view
        if (position + 1 == getItemCount()) {
            return TYPE_FOOTER;
        } else {
            return TYPE_ITEM;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //判断显示类型,来创建返回不同的View
        if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(context).inflate(R.layout.good_search_item, parent, false);
            return new MyViewHolder(view);
        } else if (viewType == TYPE_FOOTER) {
            View view = LayoutInflater.from(context).inflate(R.layout.foot_view, parent, false);
            return new FootViewHolder(view);
        }
//        View view = LayoutInflater.from(context).inflate(R.layout.good_search_item,parent,false);
//        return new MyViewHolder(view);
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof MyViewHolder) {
            MyViewHolder myViewHolder = (MyViewHolder) holder;
            Glide.with(context).load(list.get(position).get("image")).into(myViewHolder.gs_iv); //图片加载
            myViewHolder.gs_name.setText(list.get(position).get("show_name").toString());
            myViewHolder.gs_specs.setText(list.get(position).get("attributes_list_name").toString());
            myViewHolder.gs_price.setText(list.get(position).get("goods_price").toString());
        } else if (holder instanceof FootViewHolder) {
            FootViewHolder footViewHolder = (FootViewHolder) holder;
            switch (loadState) {
                case LOADING:
                    footViewHolder.foot_tv.setVisibility(View.VISIBLE);
                    footViewHolder.foot_tv.setText("正在加载中,请耐心稍等!");
                    break;
                case LOADING_COMPLETE:
                    footViewHolder.foot_tv.setVisibility(View.VISIBLE);
                    footViewHolder.foot_tv.setText("加载完成");
                    break;
                case LOADING_END:
                    footViewHolder.foot_tv.setVisibility(View.VISIBLE);
                    footViewHolder.foot_tv.setText("亲!到底线了~~~");
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size() + 1;
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        private ImageView gs_iv;
        private TextView gs_name, gs_specs, gs_price;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            gs_iv = itemView.findViewById(R.id.gs_iv);
            gs_name = itemView.findViewById(R.id.gs_name);
            gs_specs = itemView.findViewById(R.id.gs_specs);
            gs_price = itemView.findViewById(R.id.gs_price);
        }
    }

    public class FootViewHolder extends RecyclerView.ViewHolder {
        private TextView foot_tv;

        public FootViewHolder(@NonNull View itemView) {
            super(itemView);
            foot_tv = itemView.findViewById(R.id.foot_tv);
        }
    }

    /**
     * 设置加载状态
     * @param loadState 0.正在加载,1.加载完成,2.加载到底
     */
    public void setLoadState(int loadState) {
        this.loadState = loadState;
        notifyDataSetChanged();
    }
}

到这里的话,一个线性布局列表的Adapter就完成了,可能有人会疑问,如果是网格布局那怎么弄,不要着急,接下来就跟你们说说:
网格布局需要在Adapter中重写onAttachedToRecyclerView方法。首先判断当前是否为网格布局,然后给GridLayoutManager设置一个SpanSizeLookup,这是一个抽象类,里面有一个抽象方法getSpanSize,这个方法的返回值决定了每个Item占据的单元格数。

   @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if(manager instanceof GridLayoutManager){
            final GridLayoutManager gridLayoutManager = ((GridLayoutManager)manager);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    // 如果当前是footer的位置,那么该item占据2个单元格,正常情况下占据1个单元格
                    return getItemViewType(position) == TYPE_FOOTER ? gridLayoutManager.getSpanCount():1;
                }
            });
        }
    }
二. 创建适配器并设置数据
  1. 在界面初始化的时,创建适配器(这里自定义个方法,在oncreate中调用就可以了)
 private void createSearchAdapter() {
        LinearLayoutManager linearLayoutManager =  new LinearLayoutManager(this);
        goodSearch_rv.setLayoutManager(linearLayoutManager);
        goodSearchAdpter = new GoodSearchAdpter(this);
        goodSearch_rv.setAdapter(goodSearchAdpter);
    }
  1. 获取数据
   private void getData(){
        try{
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    
                    //获取后台数据相关代码
                }
            }.start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * todo Handler (主线程和子线程的通信)
     */
  @SuppressLint("HandlerLeak")
    public Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            JSONArray d = (JSONArray)msg.obj;
            switch (msg.what){
                case 1:
                    //每次请求新数据时,直接使用set数据,并刷新
                    goodSearchAdpter.setData(searchList);
                    goodSearchAdpter.notifyDataSetChanged();
                    break;
            }
        }
    };
三.为RecyclerView设置监听

设置好FooterView之后,我们还需要判断一下什么时候显示出来,这就需要调用RecyclerView的addOnScrollListener方法设置一下加载更多监听,当滑动到最后一个Item的时候,在loadingMore方法中,首先显示正在加载进度UI,然后进行网络请求,完成数据获取之后隐藏加载进度UI,加载完页数之后显示到底了的提示。看下代码:

 private void setRecyclerOnScrollListener(){
        goodSearch_rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private boolean isSlidingUpward = false; //用来标记是否正在向上滑动
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //当不滑动时
                if(newState ==RecyclerView.SCROLL_STATE_IDLE){
                    //获取最后一个完全显示的itemPosition
                    int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
                    int itemCount = manager.getItemCount();
                    // 判断是否滑动到了最后一个item,并且是向上滑动
                    if(lastItemPosition == (itemCount - 1) && isSlidingUpward){
                        loadingMore(); //加载第二页
                    }
                }
            }
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 大于0表示正在向上滑动,小于等于0表示停止或向下滑动
                isSlidingUpward = dy > 0;
            }
        });
    }
 private void loadingMore() {
        goodSearchAdpter.setLoadState(goodSearchAdpter.LOADING); //FootView显示状态
        if(pageIndex < maxPage){
            pageIndex ++;
            searchDown();
            goodSearchAdpter.setLoadState(goodSearchAdpter.LOADING_COMPLETE);
            goodSearchAdpter.notifyDataSetChanged();
        }
        if(searchList.size()<count){
            goodSearchAdpter.setLoadState(goodSearchAdpter.LOADING);
        }else{
            goodSearchAdpter.setLoadState(goodSearchAdpter.LOADING_END);
        }
    }

到这里,我们已经完成了RecyclerView的上拉加载更多功能。

但是这里的话我就遇到过一个问题我得跟大家分享下:

在加载数据这一块,我一开始是使用构造器方式创建的,每次加载数据我都会重新new adapter,而这样造成的后果就是每次上拉加载下一页时,都会重新跳回到顶部,按正常的逻辑,应该是数据位置定位到之前请求数据之前的位置(就是接着之前数据的后面),那怎么解决呢?
其实,刷新数据时,不能每次都new adapter的,应该是在刷新时把数据set进去就好了

  1. 在adapter中定义setData方法set数据,不使用构造器方式创建
    private List<Map<String, Object>> list = new ArrayList<>();
    
    public List<Map<String, Object>> getData() {
        return list;
    }
    
    public void setData(List<Map<String, Object>> list) {
        this.list= list;
    }
  1. 在界面初始化的时候,创建适配器
 private void createSearchAdapter() {
     LinearLayoutManager linearLayoutManager =  new LinearLayoutManager(this);
     goodSearch_rv.setLayoutManager(linearLayoutManager);
     goodSearchAdpter = new GoodSearchAdpter(this);
     goodSearch_rv.setAdapter(goodSearchAdpter);
 }
  1. 在数据刷新变化的时候,直接使用set数据,并刷新
  //每次请求新数据时,直接使用set数据,并刷新
   goodSearchAdpter.setData(searchList);
   goodSearchAdpter.notifyDataSetChanged();
四.封装

我们已经完成了RecyclerView的上拉加载更多功能,但是大部分的逻辑都写在了Adapter中,这样每写一个Adapter都要写一遍加载逻辑,这是很不好的,所以接下来我们对加载更多功能做一个封装,使其和Adapter完全解构,看下代码:

public class LoadMoreAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private RecyclerView.Adapter adapter;
    
    private Context context;

    // 普通布局
    private final int TYPE_ITEM = 1;
    // 脚布局
    private final int TYPE_FOOTER = 2;
    // 当前加载状态,默认为加载完成
    private int loadState;
    // 正在加载
    public final int LOADING = 1;
    // 加载完成
    public final int LOADING_COMPLETE = 2;
    // 加载到底
    public final int LOADING_END = 3;

    public LoadMoreAdapter(RecyclerView.Adapter adapter){
        this.adapter = adapter;
    }

    @Override
    public int getItemViewType(int position) {
        if(position+1 == getItemCount()){
            return TYPE_FOOTER;
        }else {
            return TYPE_ITEM;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_FOOTER) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.foot_view, parent, false);
            return new FootViewHolder(view);
        } else if (viewType == TYPE_ITEM) {
            return adapter.onCreateViewHolder(parent,viewType);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
       if (holder instanceof FootViewHolder) {
            FootViewHolder footViewHolder = (FootViewHolder) holder;
            switch (loadState) {
                case LOADING:
                    footViewHolder.foot_tv.setVisibility(View.VISIBLE);
                    footViewHolder.foot_tv.setText("正在加载中");
                    break;
                case LOADING_COMPLETE:
                    footViewHolder.foot_tv.setVisibility(View.VISIBLE);
                    footViewHolder.foot_tv.setText("加载完成");
                    break;
                case LOADING_END:
                    footViewHolder.foot_tv.setVisibility(View.VISIBLE);
                    footViewHolder.foot_tv.setText("亲!到底线了~~~");
                    break;
                default:
                    footViewHolder.foot_tv.setVisibility(View.GONE);
                    break;
            }
        }else{
           adapter.onBindViewHolder(holder,position);
       }
    }

    @Override
    public int getItemCount() {
        return adapter==null?0:adapter.getItemCount()+1;
    }

    /**
     * todo Adapter在网格布局
     * @param recyclerView
     */
    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if(manager instanceof GridLayoutManager){
            final GridLayoutManager gridLayoutManager = ((GridLayoutManager)manager);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    // 如果当前是footer的位置,那么该item占据2个单元格,正常情况下占据1个单元格
                    return getItemViewType(position) == TYPE_FOOTER ? gridLayoutManager.getSpanCount():1;
                }
            });
        }
    }


    public class FootViewHolder extends RecyclerView.ViewHolder {
        private TextView foot_tv;

        public FootViewHolder(@NonNull View itemView) {
            super(itemView);
            foot_tv = itemView.findViewById(R.id.foot_tv);
        }
    }

    /**
     * 设置上拉加载状态
     *
     * @param loadState 0.正在加载 1.加载完成 2.加载到底
     */
    public void setLoadState(int loadState) {
        this.loadState = loadState;
        notifyDataSetChanged();
    }
}

这样,构造方法中的参数变成了RecyclerView.Adapter,在LoadMoreAdapter中我们只处理加载更多功能相关的逻辑,其他逻辑交由Adapter本身处理,相当于扩展了Adapter的一些功能,adapter代码如下:

public class GoodSearchAdpter extends RecyclerView.Adapter<GoodSearchAdpter.MyViewHolder> {

    private List<Map<String, Object>> list = new ArrayList<>();
    private Context context;

    public List<Map<String, Object>> getData() {
        return list;
    }

    public void setData(List<Map<String, Object>> list) {
        this.list= list;
    }

    public GoodSearchAdpter(Context context) {
        this.context = context;
    }

    @NonNull
    @Override
    public GoodSearchAdpter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.good_search_item,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull GoodSearchAdpter.MyViewHolder holder, int position) {
        Glide.with(context).load(list.get(position).get("image")).into(holder.gs_iv);//图片加载
        holder.gs_name.setText(list.get(position).get("show_name").toString());
        holder.gs_specs.setText(list.get(position).get("attributes_list_name").toString());
        holder.gs_price.setText(list.get(position).get("goods_price").toString());
    }

    @Override
    public int getItemCount() {
        return list==null?0:list.size();
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        private ImageView gs_iv;
        private TextView gs_name, gs_specs, gs_price;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            gs_iv = itemView.findViewById(R.id.gs_iv);
            gs_name = itemView.findViewById(R.id.gs_name);
            gs_specs = itemView.findViewById(R.id.gs_specs);
            gs_price = itemView.findViewById(R.id.gs_price)}
    }

在activity中创建adapter,在原有Adapter的基础上包上一层就可以了

    private void createSearchAdapter() {
        LinearLayoutManager linearLayoutManager =  new LinearLayoutManager(this);
        goodSearch_rv.setLayoutManager(linearLayoutManager);
        goodSearchAdpter = new GoodSearchAdpter(this);
        loadMoreAdapter = new LoadMoreAdapter(goodSearchAdpter);
        goodSearch_rv.setAdapter(loadMoreAdapter);
        }

以上是关于android中如何实现上拉加载更多功能(建议收藏)的主要内容,如果未能解决你的问题,请参考以下文章

Android上拉加载更多ListView——PulmListView

Android RecyclerView上拉加载更多item点击事件(显示获取的数据)

Android实现RecyclerView的下拉刷新和上拉加载更多

[Android] Android 支持下拉刷新上拉加载更多 的 XRecyclerview

使用SwipeRefreshLayout和RecyclerView实现仿“简书”下拉刷新和上拉加载更多

使用SwipeRefreshLayout和RecyclerView实现仿“简书”下拉刷新和上拉加载更多