Android-RecycleView上拉加载更多

5.0之后 推出的RecycleView来代替ListView,可以说RecycleView和ListView比起有过之而无不及,下面这篇博客主要来实现RecyclerView的上拉加载更多功能。
  基本思路是让RecyclerView的Adapter加载两种布局,第一个布局来显示主界面,第二个布局来显示上拉加载时的提示信息,让RecyclerView监听是否滑动到最后一个item,如果是,则调用上拉刷新的逻辑,拉取远程数据,并显示第二个布局。等加载完毕时,刷新Adapter,并隐藏第二个布局.

下面主要是针对 对RecyclerAdapter的修饰封装,一般我们在使用RecycleView的时候会将RecycleAdapter和RecycleHolder分开进行封装,在使用的时候,就会很方便(这两个类就不贴了,各自有各自的实现)。

先贴两个博客地址翔哥和傻子斌的添加haedView和footVIew的具体操作,因为下拉刷新和上拉加载就是基于添加这个来实现。

1.核心实现

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

    }
}

@Override
public int getItemCount() {
    return super.getItemCount() + 1;
}

用过listView的人都知道这两个方法,可以说很大程度上和listView一样,不过ListView有自带的addHead 和 addFoot的方法,RecycleView则没有,所以就需要我们在Adapter中对其进行实现。

2.实现上拉加载更多

public abstract class BasePullUpRecyclerAdapter extends BaseRecyclerAdapter {

public static final int TYPE_FOOTER = 0;//两种状态 footview显示的时候和不显示的一般item
public static final int TYPE_ITEM = 1;

public static final int STATE_INVISIBLE = 0;//footView的四种状态   不可见  加载中  没有更多  没有数据
public static final int STATE_LOADING = 1;
public static final int STATE_NO_MORE = 2;
public static final int STATE_NO_DATA = 3;

protected int state = STATE_LOADING;//默认为加载中
protected FooterView footerView;//footView
private OnPullUpListener pullUpListener;//上拉监听

public BasePullUpRecyclerAdapter(RecyclerView v, Collection datas, int itemLayoutId) {
    super(v, datas, itemLayoutId);
    v.addOnScrollListener(new BasePullUpScrollListener());//将自定义的监听添加进Adapter
    footerView = new FooterView(cxt);//初始化自定义的FootView
}

@Override
public int getItemViewType(int position) {//根据不同的位置设置不同的类型状态
    if (position == getItemCount() - 1) {
        return TYPE_FOOTER;
    } else {
        return TYPE_ITEM;

    }
}

@Override
public int getItemCount() {//
    return super.getItemCount() + 1;
}

@Override
public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == TYPE_ITEM) {
        return super.onCreateViewHolder(parent, viewType);
    } else if (viewType == TYPE_FOOTER) {
        refreshFooterView();
        return new RecyclerHolder(footerView);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerHolder holder, int position) {
    if (position == getItemCount() - 1) {
        //因为已经在footerview写死了,所以这里就不用再去设置
        //没有数据的时候也不显示footer
        if (position == 0) {
            getFooterView().setVisibility(View.GONE);
        }
    } else {
        super.onBindViewHolder(holder, position);
    }
}

public int getState() {//返回状态
    return this.state;
}

public void setState(int state) {//设置不同的状态然后更新footView
    this.state = state;
    refreshFooterView();
}

/**
 * 获取底部的FooterView
 *
 * @return
 */
public FooterView getFooterView() {
    return this.footerView;
}

/**
 * 滚动到底部时的监听器
 *
 * @param l
 */
public void setPullUpListener(OnPullUpListener l) {
    this.pullUpListener = l;
}

private void refreshFooterView() {
    switch (state) {
        case STATE_INVISIBLE:
            footerView.setInVisibleState();
            break;
        case STATE_LOADING:
            footerView.setLoadingState();
            break;
        case STATE_NO_MORE:
            footerView.setNoMoreState();
            break;
        case STATE_NO_DATA:
            footerView.setNoDataState();
            break;
    }
} ········

3.实现对不同的Layout进行适配

 /**
 * 监听,判断RecyclerView滚动到底部时,加载onBottom方法
 */
public class BasePullUpScrollListener extends RecyclerView.OnScrollListener {
    public static final int LINEAR = 0;
    public static final int GRID = 1;
    public static final int STAGGERED_GRID = 2;

    //标识RecyclerView的LayoutManager是哪种
    protected int layoutManagerType;
    // 瀑布流的最后一个的位置
    protected int[] lastPositions;
    // 最后一个的位置
    protected int lastVisibleItem;

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 >=
                getItemCount() && pullUpListener != null) {
            pullUpListener.onBottom(state);//回调加载更多监听
        }
    }

      //根据不同的Layout类型处理FootView
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            layoutManagerType = LINEAR;
        } else if (layoutManager instanceof GridLayoutManager) {
            layoutManagerType = GRID;
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            layoutManagerType = STAGGERED_GRID;
        } else {
            throw new RuntimeException(
                    "Unsupported LayoutManager used. Valid ones are " +
                            "LinearLayoutManager, GridLayoutManager and " +
                            "StaggeredGridLayoutManager");
        }

        switch (layoutManagerType) {
            case LINEAR:
                lastVisibleItem = ((LinearLayoutManager) layoutManager)
                        .findLastVisibleItemPosition();
                break;
            case GRID:
                lastVisibleItem = ((GridLayoutManager) layoutManager)
                        .findLastVisibleItemPosition();
                break;
            case STAGGERED_GRID:
                StaggeredGridLayoutManager staggeredGridLayoutManager
                        = (StaggeredGridLayoutManager) layoutManager;
                lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
                staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
                lastVisibleItem = findMax(lastPositions);
                break;
        }
    }

    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }
}

4.自定义的footView(可根据自己需求自定义)

  public class FooterView extends LinearLayout {
protected String loadingText = "加载中…";
protected String noMoreText = "已加载全部";
protected String noDataText = "暂无内容";

private final TextView textView;
private final ProgressBar progressBar;

public FooterView(Context context) {
    super(context);
    textView = new TextView(context);
    progressBar = new ProgressBar(context);
    init(context);
}


public void init(Context context) {
    this.setOrientation(HORIZONTAL);
    this.setGravity(Gravity.CENTER);
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER;
    params.height = dip2px(23);
    this.setLayoutParams(params);

    progressBar.setIndeterminate(true);
    LayoutParams progressBarparams = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    progressBarparams.width = progressBarparams.height = dip2px(22);
    progressBar.setLayoutParams(progressBarparams);

    LayoutParams textViewparams = new LayoutParams(LayoutParams.WRAP_CONTENT, dip2px(20));
    textView.setTextColor(0xff666666);
    textView.setTextSize(16);
    textView.setLayoutParams(textViewparams);

    this.addView(progressBar);
    this.addView(textView);
}

public void setText(CharSequence s) {
    textView.setText(s);
}

public void setTextColor(int color) {
    textView.setTextColor(color);
}

public void setTextSize(float size) {
    textView.setTextSize(size);
}

public void setNoDataState() {
    this.setVisibility(View.VISIBLE);
    progressBar.setVisibility(View.GONE);
    textView.setVisibility(View.VISIBLE);
    textView.setText(noDataText);
}

public void setNoMoreState() {
    this.setVisibility(View.VISIBLE);
    progressBar.setVisibility(View.GONE);
    textView.setVisibility(View.VISIBLE);
    textView.setText(noMoreText);
}

public void setLoadingState() {
    this.setVisibility(View.VISIBLE);
    progressBar.setVisibility(View.VISIBLE);
    textView.setVisibility(View.VISIBLE);
    textView.setText(loadingText);
}

public ProgressBar getProgressBar() {
    return progressBar;
}

public void setInVisibleState() {
    this.setVisibility(View.GONE);
}

public void setLoadingText(String loadingText) {
    this.loadingText = loadingText;
}

public void setNoMoreText(String noMoreText) {
    this.noMoreText = noMoreText;
}

public void setNoDataText(String noDataText) {
    this.noDataText = noDataText;
}


public int dip2px(float dpValue) {
    Resources r = getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            dpValue, r.getDisplayMetrics());
    return (int) px;
}

}

之所以都用代码来写,不用xml布局,为了减少一个xml布局,实际这个View的布局也不复杂,一个RelativeLayout就可以搞定了。就不具体注释来说明了,都看得懂

5.具体使用

1.对适配器进行监听,设置加载中 和 加载数据

  mAdapter.setPullUpListener(new BasePullUpRecyclerAdapter.OnPullUpListener() {
        @Override
        public void onBottom(int state) {
            mAdapter.setState(BasePullUpRecyclerAdapter.STATE_LOADING);
            mPresenter.load();
        }
    });

2.在数据返回的时候对其进行处理

public void onEvent(MessageEventNew event) {
        setLoadingIndicator(false);
        if (event.code == ModelEvent.SUCCESS) {
            if (event.list == null || event.list.size() == 0) {//如果没有数据,就设置为STATE_NO_MORE
                onContentEmpty();
                mAdapter.setState(BasePullUpRecyclerAdapter.STATE_NO_MORE);
            } else {
                lastMessageId = event.list.get(event.list.size() - 1).id;
                if(lastMessageId==newLastId){//否则加载的数据和上一次加载的数据是否相同来判断是NOMORE还是有数据然后隐藏
                    mAdapter.setState(BasePullUpRecyclerAdapter.STATE_NO_MORE);
                }else {
                    mAdapter.setState(BasePullUpRecyclerAdapter.STATE_INVISIBLE);
                }
                showContent(event.list);
                newLastId = lastMessageId;
            }
        } else {
            ViewKit.shortToast(event.message);
            onNetwork();
        }
    }

你可能感兴趣的:(Android-RecycleView上拉加载更多)