SwipeRefreshLayout+RecyclerView实现下拉刷新上拉加载功能

Android Studio 的gradle中添加如下依赖,SwipeRefreshLayout在 support V4 包下,RecyclerView在V7包下,由于V7包内包涵了V4,所以就不需要添加V4的依赖了。

  compile 'com.android.support:appcompat-v7:23.0.0'
  compile 'com.android.support:recyclerview-v7:23.0.0'

实现继承自RecyclerView.Adapter<>的适配器, 实现上拉加载功能,在RecyclerView的底部添加一个footer,(根据ViewType的类型判断是添加Item还是Footer),需要重写的三个方法:

①onCreateViewHolder()
这个方法主要为每个Item inflater出一个View,但是该方法返回的是一个ViewHolder。该方法把View直接封装在ViewHolder中,然后我们面向的是ViewHolder这个实例,当然这个ViewHolder需要我们自己去编写。直接省去了当初的convertView.setTag(holder)和convertView.getTag()这些繁琐的步骤。

②onBindViewHolder()
这个方法主要用于适配渲染数据到View中。方法提供给你了一个viewHolder,而不是原来的convertView。

③getItemCount()
这个方法就类似于BaseAdapter的getCount方法了,即总共有多少个条目。

public class MyAdapter  extends RecyclerView.Adapter {
    public enum LoadStatus{
        CLICK_LOAD_MORE,//上拉加载更多
        LOADING_MORE//正在加载更多
    }
    private LoadStatus mLoadStatus = LoadStatus.CLICK_LOAD_MORE;//上拉加载的状态
    private static final int VIEW_TYPE_FOOTER = 0;
    private static final int VIEW_TYPE_ITEM = 1;
    private List mList;
    private Context mContext;


    public MyAdapter(Context context, List list) {
        mContext = context;
        mList = list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_FOOTER) {
            return onCreateFooterViewHolder(parent, viewType);
        } else if (viewType == VIEW_TYPE_ITEM) {
            return onCreateItemViewHolder(parent, viewType);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case VIEW_TYPE_ITEM:
                onBindItemViewHolder(holder, position);
                break;
            case VIEW_TYPE_FOOTER:
                onBindFooterViewHolder(holder, position, mLoadStatus);
                break;
            default:
                break;
        }
    }

    public RecyclerView.ViewHolder onCreateFooterViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.footer_layout,parent,false);
        return new FooterViewHolder(view);
    }

    public RecyclerView.ViewHolder onCreateItemViewHolder(ViewGroup parent, int viewType) {
        View view =LayoutInflater.from(mContext).inflate(R.layout.item_layout,parent,false);
        return new ItemViewHolder(view);
    }

    public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int poition, LoadStatus loadStatus) {
        FooterViewHolder viewHolder = (FooterViewHolder) holder;
        switch (loadStatus) {
            case CLICK_LOAD_MORE:
                viewHolder.mLoadingLayout.setVisibility(View.GONE);
viewHolder.mClickLoad.setVisibility(View.VISIBLE);
 break;
            case LOADING_MORE:
                viewHolder.mLoadingLayout.setVisibility(View.VISIBLE);
viewHolder.mClickLoad.setVisibility(View.GONE);
 break;
        }
    }

    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        ItemViewHolder viewHolder = (ItemViewHolder) holder;
        viewHolder.mTextView.setText(getItem(position));
    }

    @Override
    public int getItemCount() {
        return mList.size() + 1;
    }
   public  void refresh(){
       notifyDataSetChanged();
   }
    public String getItem(int position) {
        return mList.get(position);
    }

    public void addAll(List list) {
        this.mList.addAll(list);
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        if (position + 1 == getItemCount()) {//最后一条为FooterView
            return VIEW_TYPE_FOOTER;
        }

        return VIEW_TYPE_ITEM;
    }

    public void reSetData(List list) {
        this.mList = list;
        notifyDataSetChanged();
    }

    public void setLoadStatus(LoadStatus loadStatus) {
        this.mLoadStatus = loadStatus;
    }
}

  class FooterViewHolder extends  RecyclerView.ViewHolder{
        public LinearLayout mLoadingLayout;
        public TextView mClickLoad;
        public FooterViewHolder(View itemView) {
            super(itemView);
            mLoadingLayout=(LinearLayout) itemView.findViewById(R.id.loading);
            mClickLoad=(TextView) itemView.findViewById(R.id.click_load_txt);
/* mClickLoad.setOnClickListener(new View.OnClickListener() {
//添加点击加载更多监听
                @Override
                public void onClick(View view) {
                    loadMore();
                }
            });*/
        }
    }
  class ItemViewHolder extends  RecyclerView.ViewHolder{

          public TextView mTextView;
          public ItemViewHolder(View itemView) {
              super(itemView);
              mTextView = (TextView) itemView.findViewById(R.id.textView);
          }
      }

footer的layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:gravity="center_horizontal"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/loading"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="horizontal">
        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:text="正在加载..."/>
    LinearLayout>

    <TextView
        android:id="@+id/click_load_txt"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:text="点击加载更多"
        android:visibility="gone"/>

RelativeLayout>

Item的layout


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:gravity="center"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    />
LinearLayout>

activity_main

"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.yzppp.recycle.MainActivity">

    .support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        .support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        .support.v7.widget.RecyclerView>

    .support.v4.widget.SwipeRefreshLayout>

MainActivity的实现,下拉刷新通过SwipeRefreshLayout.OnRefreshListener()
接口来实现。

public class MainActivity extends Activity {
private RecyclerView mRecyclerView;
private  SwipeRefreshLayout mSwipeRefreshLayout;
private MyAdapter mAdapter;
    private int mLastVisibleItemPosition=0;
    private LinearLayoutManager mLayoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView= (RecyclerView) findViewById(R.id.recyclerView);
        mSwipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        mLayoutManager=new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter=new MyAdapter(this,getData("init"));
        mRecyclerView.setAdapter(mAdapter);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
                         @Override
                         public void onRefresh() {
                        new Thread(){
                          @Override
                          public void run() {
                              try{
                                Thread.sleep(3000);
                                final List list=getData("refresh");
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mAdapter.reSetData(list);
                                        mSwipeRefreshLayout.setRefreshing(false);
                                    }
                                });
                              }
                              catch (InterruptedException e){
                                  e.printStackTrace();
                              }
                          }
                      }.start();
                      }
             });

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override//滚动状态变化时回调
            public void onScrollStateChanged(RecyclerView recyclerView, int newState)    {

                super.onScrollStateChanged(recyclerView, newState);
               // mLastVisibleItemPosition=mLayoutManager.findLastVisibleItemPosition();
                //滑动停止并且底部不可滚动(即滑动到底部) 加载更多
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&!(ViewCompat.canScrollVertically(recyclerView,1))
                       ){
                         loadMore();

                }
            }

            @Override//滚动时回调
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

            }
        });
   }

    public void loadMore(){
        mAdapter.setLoadStatus(MyAdapter.LoadStatus.LOADING_MORE);
        mAdapter.refresh();
        new Thread(){
            @Override
            public void run() {
                try{
                    Thread.sleep(3000);
                    final List list=getData("load more");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.addAll(list);

                            mAdapter.setLoadStatus(MyAdapter.LoadStatus.CLICK_LOAD_MORE);
                        }
                    });
                }catch (InterruptedException e){
                  e.printStackTrace();
                };
            }
        }.start();
    }
    public  List getData(String flag){
        int idx=1;
        if(mAdapter!=null){
            idx=mAdapter.getItemCount();
        }
        List list=new ArrayList<>(10);
        for (int i=0;i<10;i++){
            list.add(flag+":"+(idx+i));
        }
        return list;
    }

}

你可能感兴趣的:(android,android,studio,android)