RecyclerView上拉加载更多菜鸟自用,大神绕道

之前因为需求上啦加载要配合swip下拉刷新,结果网上找了几个框架都不能满足我的需求,最后终于找到个吧但是屏蔽了他的下拉事件也导致了不能swip下拉刷新,所以就下决心自己写了一个上拉加载!

直接上代码有需要的可以直接撸走!改下名字就可以直接使用了! 具体流程大家运行起了自己看看代码就行了挺简单的!

先上脚布局视图

public class LoadingFooter extends RelativeLayout{
    protected State mState = State.Normal;
    private View mLoadingView;
    private View mNetworkErrorView;
    private View mTheEndView;
    private ProgressBar mLoadingProgress;
    private TextView mLoadingText;

    public LoadingFooter(Context context) {
        this(context, null);
    }

    public LoadingFooter(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadingFooter(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void init(Context context) {
        inflate(context, R.layout.view_recycler_footer, this);
        setOnClickListener(null);
        setState(State.Normal, true);
    }

    public State getState() {
        return mState;
    }

    public void setState(State status) {
        setState(status, true);
    }

    public void setState(State status, boolean showView) {
        if (mState == status) {
            return;
        }
        mState = status;
        switch (status) {
            case Normal:
                setOnClickListener(null);
                if (mLoadingView != null) {
                    mLoadingView.setVisibility(GONE);
                }

                if (mTheEndView != null) {
                    mTheEndView.setVisibility(GONE);
                }

                if (mNetworkErrorView != null) {
                    mNetworkErrorView.setVisibility(GONE);
                }
                break;
            case Loading:
                setOnClickListener(null);
                if (mTheEndView != null) {
                    mTheEndView.setVisibility(GONE);
                }

                if (mNetworkErrorView != null) {
                    mNetworkErrorView.setVisibility(GONE);
                }

                if (mLoadingView == null) {
                    ViewStub viewStub = (ViewStub) findViewById(R.id.loading_viewstub);
                    mLoadingView = viewStub.inflate();
                    mLoadingProgress = (ProgressBar) mLoadingView.findViewById(R.id.pg_loading);
                    mLoadingText = (TextView) mLoadingView.findViewById(R.id.tv_loaddata);
                } else {
                    mLoadingView.setVisibility(VISIBLE);
                }
                mLoadingView.setVisibility(showView ? VISIBLE : GONE);
                mLoadingProgress.setVisibility(View.VISIBLE);
                break;
            case TheEnd:
                setOnClickListener(null);
                if (mLoadingView != null) {
                    mLoadingView.setVisibility(GONE);
                }

                if (mNetworkErrorView != null) {
                    mNetworkErrorView.setVisibility(GONE);
                }

                if (mTheEndView == null) {
                    ViewStub viewStub = (ViewStub) findViewById(R.id.end_viewstub);
                    mTheEndView = viewStub.inflate();
                } else {
                    mTheEndView.setVisibility(VISIBLE);
                }

                mTheEndView.setVisibility(showView ? VISIBLE : GONE);
                break;
            case NetWorkError:
                if (mLoadingView != null) {
                    mLoadingView.setVisibility(GONE);
                }

                if (mTheEndView != null) {
                    mTheEndView.setVisibility(GONE);
                }

                if (mNetworkErrorView == null) {
                    ViewStub viewStub = (ViewStub) findViewById(R.id.network_error_viewstub);
                    mNetworkErrorView = viewStub.inflate();
                } else {
                    mNetworkErrorView.setVisibility(VISIBLE);
                }
                mNetworkErrorView.setVisibility(showView ? VISIBLE : GONE);
                break;
            default:
                break;
        }
    }

    public enum State {
        Normal, TheEnd, Loading, NetWorkError
    }
}

脚视图布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/loading_view"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:gravity="center"
    android:orientation="vertical">

    <ViewStub
        android:id="@+id/loading_viewstub"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout="@layout/item_recycler_footer_loading" />

    <ViewStub
        android:id="@+id/end_viewstub"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout="@layout/item_recycler_footer_end" />

    <ViewStub
        android:id="@+id/network_error_viewstub"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout="@layout/item_recycler_footer_network_error" />

</LinearLayout>






item_recycler_footer_loading

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/loading_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <ProgressBar
        android:id="@+id/pg_loading"
        android:layout_width="30dp"
        android:layout_height="30dp"  />

    <TextView
        android:textColor="#FF159121"
        android:textSize="18sp"
        android:layout_marginLeft="20dp"
        android:id="@+id/tv_loaddata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="loading..."
        android:visibility="visible" />

</LinearLayout>


item_recycler_footer_end

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal">

    <TextView
        android:textColor="#FF159121"
        android:id="@+id/loading_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="-- end --"
        android:textSize="14sp" />
</LinearLayout>

item_recycler_footer_network_error

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/loading_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FF159121"
        android:text="-- 网络异常,请刷新重试 --"
        android:textSize="14sp" />
</LinearLayout>

加载更多需要的adapter


public abstract class RecLoadMoreAdapter<T> extends RecyclerView.Adapter {
    private static final int TYPE_LOAD_MORE = Integer.MIN_VALUE + 1; //脚布局类型标记
    private FrameLayout mFooterParentView; //脚布局容器
    private View mFooterView; //脚布局
    protected List<T> mModule = new ArrayList<>(); //数据源
    private boolean isShowFooter = false; //是否显示脚布局的标记

    public RecLoadMoreAdapter() {
    }

    /**
     * 添加数据
     * @param
     */
    public void add(List<T> data){
        mModule.addAll(data);
        this.notifyDataSetChanged();
    }

    /**
     * 清除数据源
     */
    public void clear(){mModule.clear();}

    @Override
    public int getItemViewType(int position) {
        if (isShowFooter && position == getItemCount() - getFooterCount()){
            return TYPE_LOAD_MORE;
        }
        return superItemViewType(position);
    }

    /**
     * 返回正常类型的布局标记
     * @param position
     * @return
     */
    private int superItemViewType(int position) {
        return  super.getItemViewType(position);  //父类默认返回的就是0
    }

    private int getFooterCount() {
        if (isShowFooter){
            return 1;
        }
        return 0;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == TYPE_LOAD_MORE){
            if(mFooterParentView == null){
                mFooterParentView = new FrameLayout(parent.getContext());
                parent.addView(mFooterParentView);
                if(mFooterView != null){
                   mFooterParentView.addView(mFooterView);
                }
            }
            return new ViewHolderLoadMore(mFooterParentView);
        }
        //此处子类必须实现子 返回自身的holder
        return superSelfViewHolder(parent,viewType);
    }

    /**
     * 子类必须实现自身的viewholder
     *
     * @param parent
     * @param viewType
     * @return
     */
    protected abstract RecyclerView.ViewHolder superSelfViewHolder(ViewGroup parent, int viewType);

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(position != getItemCount() - getFooterCount()){
            superOnBindViewholder(holder,position);
        }
    }

    /**
     * 子类选择性实现  为自身控件赋值
     * @param holder
     * @param position
     */
    protected void superOnBindViewholder(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        int count = mModule == null ? 0 : this.mModule.size();
        return getFooterCount() + count;
    }

    static class ViewHolderLoadMore extends  RecyclerView.ViewHolder{

         ViewHolderLoadMore(View itemView) {
            super(itemView);
        }
    }

    /**
     * 设置脚布局
     * @param view
     */
    public void setFooterView(View view){
        mFooterView = view;
        isShowFooter = true;
        if(mFooterParentView != null && mFooterParentView.getChildCount() ==0){
            mFooterParentView.addView(mFooterView);
        }
    }

    /**
     * 去除脚布局
     */
    public void removeFooterView(){
        isShowFooter = false;
        notifyDataSetChanged();
    }
}

加载更多时需要使用的接口

public interface OnLoadMore {
    void onLoadMore(View view);
}

滚动监听

public class LoadMoreScrollLisenter extends RecyclerView.OnScrollListener implements OnLoadMore {
    protected LayoutManagerType layoutManagerType;

    private int[] lastPositions;

    private int lastVisibleItemPosition;

    private int currentScrollState = 0;

    private int minPositionToEndless = 1;

    public LoadMoreScrollLisenter(){ }

    public LoadMoreScrollLisenter(int minPositionToEndless){
        this.minPositionToEndless = minPositionToEndless;
    }

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

        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();

        if (layoutManagerType == null) {
            if (layoutManager instanceof LinearLayoutManager) {
                layoutManagerType = LayoutManagerType.LinearLayout;
            } else if (layoutManager instanceof GridLayoutManager) {
                layoutManagerType = LayoutManagerType.GridLayout;
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                layoutManagerType = LayoutManagerType.StaggeredGridLayout;
            } else {
                throw new RuntimeException("Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager");
            }
        }

        switch (layoutManagerType) {
            case LinearLayout:
                lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                break;
            case GridLayout:
                lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
                break;
            case StaggeredGridLayout:
                StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
                if (lastPositions == null) {
                    lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
                }
                staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
                lastVisibleItemPosition = findMax(lastPositions);
                break;
        }
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        currentScrollState = newState;
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        int visibleItemCount = layoutManager.getChildCount();
        int totalItemCount = layoutManager.getItemCount();
        if ((visibleItemCount > 0 && currentScrollState == RecyclerView.SCROLL_STATE_IDLE && (lastVisibleItemPosition) >= totalItemCount - minPositionToEndless)) {
            onLoadMore(recyclerView);
        }
    }

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

    @Override
    public void onLoadMore(final View view) { }

    public enum LayoutManagerType {
        LinearLayout,
        StaggeredGridLayout,
        GridLayout
    }
}

在Activity或者其他里面的正式使用

public class text extends Activity {
    private RecyclerView mRc;
    private List<String> mModule;
    private LoadingFooter mFooter;
    private AlreadyAdapter mAdapter;
    private int lastPosition = 0; //上一次的加载数量
    private int size = 10; //每次默认加载10个
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text);
        initData();
        initUI();
    }

    private void initData() {
            mModule = new ArrayList<>();
            for(int x = 0 ; x < 50;x++){
                mModule.add("订单~~~~~~~"+x);
            }

    }

    private void initUI() {
        mRc = (RecyclerView) findViewById(R.id.rc);
        mRc.setOverScrollMode(View.OVER_SCROLL_NEVER);//去除阴影
        mAdapter = new AlreadyAdapter();
        LinearLayoutManager lineManger = new LinearLayoutManager(this);
        lineManger.setOrientation(LinearLayoutManager.VERTICAL);
        mRc.setLayoutManager(lineManger);
        mRc.addOnScrollListener(mOnScrollListener);
        mRc.setAdapter(mAdapter);
        /**
         * 添加脚布局
         */
        if(mFooter == null && mModule.size() > 0){
            mFooter = new LoadingFooter(UiUtils.getContext());
            mAdapter.setFooterView(mFooter);
        }

        getFirstData();//第一次请求数据或是下拉刷新的时候
    }

    private void getFirstData() {
        getData(true);
    }

    private void getData(final boolean isClear) {
        if(mModule.size() == 0 ){
            return;
        }

        if(mFooter.getState() == LoadingFooter.State.Loading || (!isClear && mFooter.getState()
                == LoadingFooter.State.TheEnd)){
            return;
        }

        if(!isClear){ //只有不是下拉刷新或者第一次进入的时候才显示脚布局  也可以讲判断条件去掉 那样一进入界面就会显示loading....中
            mFooter.setState(LoadingFooter.State.Loading);

        }

        UiUtils.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(isClear){
                    mAdapter.clear();
                }

                List<String> mData = getDataFromServer();
                if(mData == null || mData.size() < size){
                    mFooter.setState(LoadingFooter.State.TheEnd,true);
                }else{
                    mFooter.setState(LoadingFooter.State.Normal);
                }

                if(mData != null && mData.size() > 0){
                    mAdapter.add(mData);
                    lastPosition = lastPosition + mData.size() ;
                }
            }
        },1000);

    }

    /**
     * 从服务器获取数据
     * @return
     */
    protected List<String> getDataFromServer() {

        try {
            int end = lastPosition + size > mModule.size()? mModule.size() : lastPosition + size;
            return mModule.subList(lastPosition,end);
        }catch (Exception e){
            Log.d("tag",e.toString());
        }
        return null;
    }

    private LoadMoreScrollLisenter mOnScrollListener = new LoadMoreScrollLisenter(1) {
        @Override
        public void onLoadMore(View view) {
            super.onLoadMore(view);
            getData(false);
        }
    };

    class AlreadyAdapter extends RecLoadMoreAdapter<String> {


        @Override
        protected RecyclerView.ViewHolder superSelfViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(UiUtils.getContext()).inflate(R.layout.item_already,parent,false);
            return new ViewHolders(view);
        }

        @Override
        protected void superOnBindViewholder(RecyclerView.ViewHolder holder, int position) {
            ViewHolders holders = (ViewHolders) holder;
            holders.tv.setText(mModule.get(position));
        }

         class ViewHolders extends RecyclerView.ViewHolder{
            TextView tv;
            ViewHolders(View itemView) {
                super(itemView);
                tv = (TextView) itemView.findViewById(R.id.tv_already);
            }
        }
    }
}


//布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
   <android.support.v7.widget.RecyclerView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/rc">

   </android.support.v7.widget.RecyclerView>
</LinearLayout>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,904评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,581评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,527评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,463评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,546评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,572评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,582评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,330评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,776评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,087评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,257评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,923评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,571评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,192评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,436评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,145评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,127评论 2 352

推荐阅读更多精彩内容