Android RecyclerView上拉加载和下拉刷新(基础版)

这里讲述的是用谷歌原生的SwipeRefreshLayout,进行刷新,以及利用RecycleView的滚动事件,判断是否到最后一个item,进行加载更多,这里加载更多是在RecycleView的适配器中使用不同item进行完成的。

这是activity的xml布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

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

  <android.support.v7.widget.RecyclerView
   android:id="@+id/recyclerview"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#F0F0F0"
   android:clipToPadding="false"
   android:paddingBottom="16dp"
   android:paddingTop="16dp"/>

 </android.support.v4.widget.SwipeRefreshLayout>

 <com.rey.material.widget.ProgressView
  android:id="@+id/progress_loading_main"
  app:pv_autostart="true"
  app:pv_circular="true"   app:pv_progressStyle="@style/Material.Drawable.CircularProgress"
  app:pv_progressMode="indeterminate"
  android:layout_width="50dp"
  android:layout_height="50dp"
  android:visibility="gone"
  android:layout_centerInParent="true"/>
</RelativeLayout>

接下来是对应activity中的代码:

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.retrofit.wangfei.viewpagertablayout.util.Constance;
import com.retrofit.wangfei.viewpagertablayout.R;
import com.retrofit.wangfei.viewpagertablayout.adapter.MyRecycleViewAdapter;
import com.rey.material.widget.ProgressView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


public class HomeFragment extends Fragment {

 @Bind(R.id.recyclerview)
 RecyclerView recyclerview;
 @Bind(R.id.swipe_refresh_layout)
 SwipeRefreshLayout swipeRefreshLayout;
 @Bind(R.id.progress_loading_main)
 ProgressView progress_loading_main; // 加载数据时显示的进度圆圈
 private LinearLayoutManager mRecycleViewLayoutManager;

 private int mPageNum = 1;

 private List<String> lists = new ArrayList<>();
 private MyRecycleViewAdapter mAdapter;

 public static HomeFragment newInstance() {
  HomeFragment fragment = new HomeFragment();
  return fragment;
 }

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.fragment_home, container, false);
  ButterKnife.bind(this, view);
  return view;
 }

 /**在onCreateView方法后执行*/
 @Override
 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
  super.onViewCreated(view, savedInstanceState);
  mAdapter = new MyRecycleViewAdapter(lists,getActivity());
  initRecyclerView();
  swipeRefreshLayout.setColorSchemeResources(Constance.colors);//设置下拉刷新控件变换的四个颜色
  recyclerview.setAdapter(mAdapter);
  recyclerViewOnItemClickListener();
  refresh();
  loadMore(mAdapter);
  progress_loading_main.setVisibility(View.VISIBLE);
  initData();
 }

 @Override
 public void onDestroyView() {
  super.onDestroyView();
  ButterKnife.unbind(this);
 }

 /**进入页面的初始化数据*/
 private void initData(){
  new Handler().postDelayed(new Runnable() {

   @Override
   public void run() {
    netNewsList(true);
    progress_loading_main.setVisibility(View.GONE);
   }
  }, 2000);
 }

 /**RecyclerView每个item的点击事件*/
 private void recyclerViewOnItemClickListener() {
  mAdapter.setOnItemClickListener(new MyRecycleViewAdapter.OnItemClickListener() {
   @Override
   public void onItemClick(View view, int position) {
    Snackbar.make(view, "fly", Snackbar.LENGTH_SHORT).show();
   }
  });
 }

 /**
  * 初始化RecyclerView
  */
 private void initRecyclerView() {
//  recyclerview.setItemAnimator(new DefaultItemAnimator());
//  recyclerview.setHasFixedSize(true);
  mRecycleViewLayoutManager = new LinearLayoutManager(getActivity());
  recyclerview.setLayoutManager(mRecycleViewLayoutManager); // 设置RecycleView,显示是ListView还是gridView还是瀑布流

 }

 /**下拉刷新*/
 private void refresh() {
  swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
   @Override
   public void onRefresh() {
    new Handler().postDelayed(new Runnable() {

     @Override
     public void run() {
      netNewsList(true);
      swipeRefreshLayout.setRefreshing(false); // 停止刷新
     }
    }, 2000);
   }
  });
 }

 /**
  * 设置上拉加载更多
  *
  * @param adapter RecyclerView适配器
  */
 public void loadMore(final MyRecycleViewAdapter adapter) {
  recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {

   private int lastVisibleItem;

   @Override
   public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);
    lastVisibleItem = mRecycleViewLayoutManager.findLastVisibleItemPosition(); // 滑动到最后一个
   }

   @Override
   public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);

    // 效果在暂停时显示, 否则会导致重绘异常
    if (newState == RecyclerView.SCROLL_STATE_IDLE
      && lastVisibleItem + 1 == adapter.getItemCount()) {

     if (lists != null && lists.size() >= 10) { // 真实开发中要设置mNews.size()大于加载分页显示的个数
      adapter.loadLayout.setVisibility(View.VISIBLE);
      //加载更多
      new Handler().postDelayed(new Runnable() {

       @Override
       public void run() {
        netNewsList(false);
       }
      }, 2000);
     }
    }
   }
  });
 }

 /**
  * 从网络加载数据列表
  *
  * @param isRefresh 是否刷新 true 为刷新,false为不刷新
  */
 private void netNewsList(boolean isRefresh) {
//  viewDelegate.showLoading();
  if (isRefresh) {
   mPageNum = 1;
  } else {
   mPageNum++;
  }

  if (isRefresh) {
   if (!lists.isEmpty()) {
    lists.clear();
   }
  }
  // TODO 这里把页数mPageNum上传到服务端
  lists.clear();
  lists.addAll(getData());
  mAdapter.notifyDataSetChanged();
 }

 private List<String> list = new ArrayList<>();
 private List<String> getData() {
  for (int i = 0; i < 10; i++) {
   list.add(i + "");
  }
  return list;
 }
}

接下来是RecycleView适配器中的xml文件:

这是正常item的布局,至于用CardView是为了让item展示出来的效果更好看

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="wrap_content">

 <TextView
  android:id="@+id/text"
  android:layout_width="match_parent"
  android:layout_height="50dp"
  android:text=""
  android:gravity="center"/>

</android.support.v7.widget.CardView>

这是现实上拉加载的布局文件,作为不同item共同展示在RecycleView上面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:id="@+id/load_layout"
 android:visibility="gone"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:orientation="horizontal"
 android:paddingBottom="12dip"
 android:paddingTop="12dip">

 <com.rey.material.widget.ProgressView
  app:pv_autostart="true"
  app:pv_circular="true"
  app:pv_progressStyle="@style/Material.Drawable.CircularProgress"
  app:pv_progressMode="indeterminate"
  android:layout_width="24dp"
  android:layout_height="24dp" />

 <TextView
  android:id="@+id/more_data_msg"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="16sp"
  android:layout_marginLeft="10dp"
  android:text="正在加载..." />
</LinearLayout>

下面我们看看RecycleView适配器的写法:

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.retrofit.wangfei.viewpagertablayout.R;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Android Studio
 * Description: RecycleView的适配器
 */
public class MyRecycleViewAdapter extends RecyclerView.Adapter {

 private final static int TYPE_ITEM = 0X01;
 private final static int TYPE_FOOTER = 0x02;

 private List<String> lists;
 private Activity context;

 public LinearLayout loadLayout;

 private OnItemClickListener mOnItemClickListener; // 声明接口

 public MyRecycleViewAdapter(List<String> lists, Activity context) {
  this.lists = lists;
  this.context = context;
 }

 @Override
 public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  if (TYPE_ITEM == viewType) {
   View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_view_item, parent,false);
   ItemViewHolder itemViewHolder = new ItemViewHolder(view);
   return itemViewHolder;
  } else {
   View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_footer, parent,false);
   loadLayout = (LinearLayout) view.findViewById(R.id.load_layout);
   return new FootViewHolder(view);
  }
 }

 @Override
 public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
  if (holder instanceof ItemViewHolder) {
   String text = lists.get(position);
   ItemViewHolder itemHolder = (ItemViewHolder) holder;
   itemHolder.text.setText(text);
  }
 }

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

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

 public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

  @Bind(R.id.text)
  TextView text;

  public ItemViewHolder(View itemView) {
   super(itemView);
   ButterKnife.bind(this,itemView);
   itemView.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
   mOnItemClickListener.onItemClick(v,getPosition());
  }
 }

 public class FootViewHolder extends RecyclerView.ViewHolder {
  public FootViewHolder(View itemView) {
   super(itemView);
  }
 }

 /**调到外部使用*/
 public void setOnItemClickListener(OnItemClickListener onItemClickListener){
  this.mOnItemClickListener = onItemClickListener;
 }

 /**定义接口*/
 public interface OnItemClickListener{
  void onItemClick(View v,int position);
 }
}


最后是刷新控件的4个不同颜色:

public interface Constance {
 /**
  * 下拉刷新控件变化的四个颜色
  */
 int[] colors = new int[] {
   android.R.color.holo_green_light, android.R.color.holo_blue_light,
   android.R.color.holo_green_light, android.R.color.holo_blue_light
 };
}

所需要的依赖库:

compile 'com.android.support:appcompat-v7:23.3.0'
 compile 'com.android.support:design:23.3.0'
 compile 'com.jakewharton:butterknife:7.0.1'
 compile 'com.android.support:support-v4:23.3.0'
 /**谷歌服务*/
 compile 'com.google.android.gms:play-services:8.4.0'
 compile 'com.github.rey5137:material:1.2.2'

到这里就结束了,完成了下拉刷新和上拉加载更多的实现。

下面说说RecyclerView的使用最基础的三点:

一:

recyclerview.setHasFixedSize(true); 
//方法用来使RecyclerView保持固定的大小,该信息被用于自身的优化。

二:

recyclerview.setItemAnimator(new DefaultItemAnimator());
ItemAnimator会根据适配器上收到的通知动画显示视图组的修改。基本上,它会自动显示添加和移除条目动画。这也不是一个简单的类,但我们发现DefaultItemAnimator已经可以运行得很好了。

三:

recyclerview.setLayoutManager(mRecycleViewLayoutManager); 

// 设置RecycleView,显示是ListView还是gridView还是瀑布流。

// 显示是ListView 
LinearLayoutManager mRecycleViewLayoutManager = new LinearLayoutManager(context);

// 显示是gridView,参数一:上下文,参数二:列数 
GridLayoutManager mGridLayoutManager=new GridLayoutManager(context, 4);

// 显示是瀑布流,参数一:显示几列,参数二:现实的方向,垂直或水平 
StaggeredGridLayoutManager mStaggeredGridLayoutManager=new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);

更多详细请参考:Android RecyclerView艺术般的控件使用完全解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。