RecyclerView上拉刷新下拉加载

先上图

RecyclerView上拉刷新下拉加载


这个上拉加载下拉刷新是在PullToRefresh的基础上写的,所以要先导入pulltoRefresh的库

下载地址:http://pan.baidu.com/s/1dFqyseP


将下载后的文件放到libs下,在gradle中添加


repositories {
    flatDir {
        dirs 'libs'
    }
}
dependencies {
    .....
    compile(name: 'pullrefresh', ext: 'aar')
    compile 'com.android.support:recyclerview-v7:25.3.0'
   ....
 }

代码附上

package com.example.administrator.refreshrecyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

import com.handmark.pulltorefresh.library.PullToRefreshBase;

/**
 * Created by Administrator on 2017/6/27 0027.
 */

public class PullToRecyclerView extends PullToRefreshBase<RecyclerView> {

    public PullToRecyclerView(Context context) {
        super(context);
    }

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

    @Override
    public Orientation getPullToRefreshScrollDirection() {
        return Orientation.VERTICAL;
    }

    @Override
    protected RecyclerView createRefreshableView(Context context, AttributeSet attributeSet) {
        return new RecyclerView(context, attributeSet);
    }

    @Override
    protected boolean isReadyForPullEnd() {
        RecyclerView refreshableView = getRefreshableView();
        return !refreshableView.canScrollVertically(1);
    }

    @Override
    protected boolean isReadyForPullStart() {
        RecyclerView refreshableView = getRefreshableView();
        return !refreshableView.canScrollVertically(-1);
    }
}

xml布局


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.refreshrecyclerview.MainActivity">

    <com.example.administrator.refreshrecyclerview.PullToRecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

代码中:


List<Integer> list = new ArrayList<>();

for (int i = 0; i < 100; i++) {
    list.add(i);
}

adapter = new MyAdapter(list);

recycler = (PullToRecyclerView) findViewById(R.id.rv);

recycler.setMode(PullToRefreshBase.Mode.BOTH);

RecyclerView recyclerView = recycler.getRefreshableView();

recyclerView.setLayoutManager(new LinearLayoutManager(this));

recyclerView.setAdapter(adapter);