项目中上拉刷新和下拉加载一直都是比较常见的;以前一般都是重写ListView或直接用PullToRefreshListView的框架;最近尝试用RecyclerView来实现下拉加载上拉刷新也是不错的。

如图是Demo的效果图:

第一个效果图是用RecyclerView实现加的几个静态数据;

第二个是参考别人写的RefreshRecyclerView来实现上拉刷新下拉加载;我只是把他的静态数据改成网络的数据;不过原先那个有点问题我发现在2次以上的刷新加载后布局会混乱刷新的item竟然复制了一份漂浮在界面上方跟着屏幕一起在滑动!感觉蛮好玩的

第三个是用的PullToRefreshListView来实现的数据和第二个一样都是网络接数据

demo的下载地址:http://download.csdn.net/detail/qq_29774291/9648634

如下是主要代码

 package com.item.my.jiejie.activity;

 import java.util.ArrayList;
import java.util.List;
import com.item.my.jiejie.R;
import com.item.my.jiejie.adpter.MyAdapterThree;
import com.item.my.jiejie.adpter.MyAdapterThree.OnItemClickListener;
import com.item.my.jiejie.view.DividerItemDecoration;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast; /**
* 用RecyclerView实现
* @author Administrator
*
*/
public class MyRecyleActivity extends Activity{
private RecyclerView mRecyclerView;
private List<String> mDataStrings;
private MyAdapterThree adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myrecyle);
initData();
mRecyclerView = (RecyclerView)findViewById(R.id.my_recyler);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyAdapterThree(this, mDataStrings);
mRecyclerView.setAdapter(adapter);
//即给RecyclerView添加分隔线
mRecyclerView.addItemDecoration(new DividerItemDecoration(MyRecyleActivity.this, LinearLayoutManager.VERTICAL));
//设置RecyclerView添加或删除条目的动画
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//给RecyclerView设置点击事件
adapter.setOnItemClickListener(new OnItemClickListener() { @Override
public void onLongClick(int position) {
// TODO Auto-generated method stub
Toast.makeText(MyRecyleActivity.this, "onLongClick你点击了:" + position, Toast.LENGTH_SHORT).show();
} @Override
public void onClick(int position) {
// TODO Auto-generated method stub
Toast.makeText(MyRecyleActivity.this, "onClick 你点击了:" + position, Toast.LENGTH_SHORT).show();
}
});
}
/**
* 添加数据
*/
private void initData() {
// TODO Auto-generated method stub
mDataStrings = new ArrayList<String>();
for (int i = 'A'; i < 'z'; i++)
{
mDataStrings.add("" + (char) i);
}
} }
 package com.item.my.jiejie.adpter;

 import java.util.List;

 import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.TextView;
import com.item.my.jiejie.R; public class MyAdapterThree extends RecyclerView.Adapter<MyAdapterThree.MyViewHolder> {
private Context mcontext;
private List<String> data;
private LayoutInflater inflater;
private OnItemClickListener mOnItemClickListener; public interface OnItemClickListener {
void onClick(int position); void onLongClick(int position);
} public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.mOnItemClickListener = onItemClickListener;
} public MyAdapterThree(Context context, List<String> data) {
this.mcontext = context;
this.data = data;
inflater = LayoutInflater.from(mcontext);
} class MyViewHolder extends ViewHolder { private TextView tv; public MyViewHolder(View view) {
super(view);
tv = (TextView) view.findViewById(R.id.id_num);
}
} @Override
public int getItemCount() {
// TODO Auto-generated method stub
return data.size();
} @Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
// TODO Auto-generated method stub
holder.tv.setText(data.get(position)); if (mOnItemClickListener != null) {
holder.itemView.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
mOnItemClickListener.onClick(position);
}
}); holder.itemView.setOnLongClickListener(new OnLongClickListener() { @Override
public boolean onLongClick(View v) {
mOnItemClickListener.onLongClick(position);
return false;
}
});
}
} @Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.item_myrecyle, parent,false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
}

重新RecyclerView来实现上拉刷新下拉加载

 package com.item.my.jiejie.activity;

 import java.util.ArrayList;
import java.util.List; import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams; import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.item.my.jiejie.R;
import com.item.my.jiejie.adpter.MyAdapterOne;
import com.item.my.jiejie.entity.Item;
import com.item.my.jiejie.view.RefreshRecyclerView;
import com.item.my.jiejie.view.RefreshRecyclerView.OnLoadMoreListener; import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.Toast; /**
* 实现
* @author Administrator
*
*/
public class RecycleActivity extends Activity{ private RefreshRecyclerView recyclerView;
private SwipeRefreshLayout mRefreshLayout;
private List<Item> lists = new ArrayList<Item>();
private MyAdapterOne adapter;
private int page= 0; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyle);
recyclerView = (RefreshRecyclerView)findViewById(R.id.lv_recycler);
mRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh_widget);
mRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light,android.R.color.holo_blue_light,android.R.color.holo_green_light);
//允许加载更多
recyclerView.setLoadMoreEnable(true);
//设置脚布局
recyclerView.setFooterResource(R.layout.item_footer);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
page = 1;
//默认加载第一个页
getHttp(page);
adapter = new MyAdapterOne(this, lists);
recyclerView.setAdapter(adapter);
mRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override
public void onRefresh() {
// TODO Auto-generated method stub
page =1;
lists.clear();
getHttp(page);
mRefreshLayout.setRefreshing(false);
}
});
recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() { @Override
public void loadMoreListener() {
// TODO Auto-generated method stub
page++;
System.out.println("加载更多" + page);
new Handler().postDelayed(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
getHttp(page);
}
}, 1000);
}
});
}
/**
* 网络请求加载数据
* @param page2 页数
*/
private String urlString = "http://111.39.245.156:8080/ccos/ddzx/getProjectByCom.appDo";
private void getHttp(int page){
RequestParams params = new RequestParams(urlString);
params.addBodyParameter("pageSize", "6");
params.addBodyParameter("pageNo", page + "");
params.addBodyParameter("pageOn", "" + true);
params.addBodyParameter("comId", "13");
x.http().post(params, new Callback.CommonCallback<String>() { @Override
public void onCancelled(CancelledException arg0) {
// TODO Auto-generated method stub } @Override
public void onError(Throwable arg0, boolean arg1) {
// TODO Auto-generated method stub
System.out.println("请求失败" +arg0);
recyclerView.notifyData();
} @Override
public void onFinished() {
// TODO Auto-generated method stub } @Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
System.out.println("请求成功" + arg0);
//lists.clear();
try {
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(arg0);
JsonObject root = element.getAsJsonObject();
JsonArray array = root.getAsJsonArray("missionsList");
for(JsonElement obj : array){
lists.add(new Gson().fromJson(obj, Item.class));
//recyclerView.notifyData();
} if(lists.size()<1){
Toast.makeText(RecycleActivity.this, "暂无记录", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
recyclerView.notifyData();
}
}
});
}
}

用PullToRefreshListView 来实现上拉刷新下拉加载更多

 package com.item.my.jiejie.activity;

 import java.util.ArrayList;
import java.util.List;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.item.my.jiejie.R;
import com.item.my.jiejie.adpter.MyAdapterTwo;
import com.item.my.jiejie.entity.Item;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast; /**
* PullToRefreshListView 来实现上拉刷新下拉加载更多
* @author Administrator
*
*/
public class PulltoActivity extends Activity{ private PullToRefreshListView mListView;
private int page = 0;
private List<Item> lists = new ArrayList<Item>();
private MyAdapterTwo adapter; @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pullto);
setView();
} private void setView() {
// TODO Auto-generated method stub
mListView = (PullToRefreshListView)findViewById(R.id.lv_listviewtwo);
mListView.setMode(Mode.BOTH);
ListView listView = mListView.getRefreshableView();
page = 1;
getHttp(page);
OnRefreshListener2<ListView> mListener2 = new OnRefreshListener2<ListView>() { @Override
public void onPullDownToRefresh(
PullToRefreshBase<ListView> refreshView) {
// TODO Auto-generated method stub
lists.clear();
adapter.notifyDataSetChanged();
page = 1;
getHttp(page);
} @Override
public void onPullUpToRefresh(
PullToRefreshBase<ListView> refreshView) {
// TODO Auto-generated method stub
page++;
getHttp(page);
}
};
mListView.setOnRefreshListener(mListener2);
adapter = new MyAdapterTwo(PulltoActivity.this,lists);
listView.setAdapter(adapter);
}
/**
* 网络请求加载数据
* @param page2 页数
*/
private String urlString = "http://111.39.245.156:8080/ccos/ddzx/getProjectByCom.appDo";
private void getHttp(int page2) {
// TODO Auto-generated method stub
RequestParams params = new RequestParams(urlString);
params.addBodyParameter("pageSize", "6");
params.addBodyParameter("pageNo", page2 + "");
params.addBodyParameter("pageOn", "" + true);
params.addBodyParameter("comId", "13");
x.http().post(params, new Callback.CommonCallback<String>() { @Override
public void onCancelled(CancelledException arg0) {
// TODO Auto-generated method stub } @Override
public void onError(Throwable arg0, boolean arg1) {
// TODO Auto-generated method stub
System.out.println(arg0 + "请求失败");
adapter.notifyDataSetChanged();
mListView.postDelayed(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
mListView.onRefreshComplete();
}
}, 800);
} @Override
public void onFinished() {
// TODO Auto-generated method stub } @Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
System.out.println("请求成功 " + arg0);
try {
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(arg0);
JsonObject root = element.getAsJsonObject();
JsonArray array = root.getAsJsonArray("missionsList");
for(JsonElement obj : array){
lists.add(new Gson().fromJson(obj, Item.class));
}
if(lists.size()<1){
Toast.makeText(PulltoActivity.this, "暂无记录", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
adapter.notifyDataSetChanged();
mListView.postDelayed(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
mListView.onRefreshComplete();
}
}, 800);
} }
});
}
}
 package com.item.my.jiejie.adpter;

 import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.item.my.jiejie.R;
import com.item.my.jiejie.entity.Item;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView; /**
* 第二个的适配器
*
* @author Administrator
*
*/
public class MyAdapterTwo extends BaseAdapter {
private Context context;
private List<Item> list; public MyAdapterTwo(Context context, List<Item> list) {
this.context = context;
this.list = list;
} @Override
public int getCount() {
// TODO Auto-generated method stub
if (list != null) {
return list.size();
} else {
return 0;
}
} @Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
} @Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
} @Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ViewHolder holder = null;
if (arg1 == null) {
holder = new ViewHolder();
arg1 = View.inflate(context, R.layout.item_mytwo, null);
holder.tv_place = (TextView) arg1.findViewById(R.id.item_place);
holder.tv_code = (TextView) arg1.findViewById(R.id.item_code);
holder.tv_time = (TextView) arg1.findViewById(R.id.item_time);
arg1.setTag(holder);
} else {
holder = (ViewHolder) arg1.getTag();
}
Date time = new Date(list.get(arg0).getRequireDtime());
DateFormat df = new SimpleDateFormat("yy-MM-dd HH:mm",Locale.getDefault());
String resultTime = df.format(time);
String misName = list.get(arg0).getMisName();
if(!TextUtils.isEmpty(misName)){
holder.tv_place.setText(misName + "");
}else {
holder.tv_place.setText("该地点暂无名称");
}
holder.tv_code.setText(list.get(arg0).getCurLoad() + "/"
+ list.get(arg0).getRequireAmount());
holder.tv_time.setText(resultTime);
return arg1;
} static class ViewHolder {
private TextView tv_place;
private TextView tv_code;
private TextView tv_time;
}
}

补充:当我们需要ScrollView上下拉刷新

提供2种简单的方式

第一种用PullToRefreshScrollView

    <com.handmark.pulltorefresh.library.PullToRefreshScrollView
android:id="@+id/pull_my_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
ptr:ptrAnimationStyle="flip"
ptr:ptrDrawable="@drawable/pull_icon_big"
ptr:ptrHeaderBackground="#6593CB"
ptr:ptrHeaderTextColor="#FFFFFF" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
        mRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_my_scrollview);
tv_text = (TextView) findViewById(R.id.tv_text);
mRefreshScrollView.setMode(Mode.PULL_FROM_START);
// 上拉监听函数
mRefreshScrollView
.setOnRefreshListener(new OnRefreshListener<ScrollView>() { @Override
public void onRefresh(
PullToRefreshBase<ScrollView> refreshView) {
// TODO Auto-generated method stub
String label = DateUtils.formatDateTime(ScrollActivity.this.getApplicationContext(),
System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
// Update the LastUpdatedLabel
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
getHttp();
}
});
//mRefreshScrollView.setRefreshing(true);

第二种用android.support.v4.widget.SwipeRefreshLayout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent" > <ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" > <TextView
android:id="@+id/tv_swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="wodsdfsf" />
</LinearLayout>
</ScrollView> </android.support.v4.widget.SwipeRefreshLayout>
package com.item.jiejie.activity;

import com.item.jiejie.R;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.widget.TextView; /**
* SwipeRefreshLayout
*
* @author Administrator
*
*/
public class SwipeActivity extends Activity {
private SwipeRefreshLayout swipeLayout;
private TextView tv_sView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
swipeLayout = (SwipeRefreshLayout)findViewById(R.id.swipe);
tv_sView =(TextView)findViewById(R.id.tv_swipe);
swipeLayout.setColorSchemeResources(android.R.color.holo_red_light,android.R.color.holo_blue_light,android.R.color.holo_green_light);
swipeLayout.setOnRefreshListener(new OnRefreshListener() { @Override
public void onRefresh() {
// TODO Auto-generated method stub
tv_sView.setText("刷新完成");
swipeLayout.postDelayed(new Runnable() { @Override
public void run() {
// TODO Auto-generated method stub
swipeLayout.setRefreshing(false);
}
}, 2000);
System.out.println("1");
}
});
}
}

RecyclerView和PullToRefreshListView的对比的更多相关文章

  1. RecyclerView 和 ListView 使用对比分析

    原文地址:http://blog.coderclock.com/2016/08/08/android/RecyclerView%20%E5%92%8C%20ListView%20%E4%BD%BF%E ...

  2. RecyclerView源码分析(一)--整体设计

    RecyclerView这个控件出来已经有一段时间了,如果看这篇文章的你,还没有使用过这个控件.那请先去学习怎样使用.不然看也白看.这里奉上一些关于介绍RecyclerView使用方法的优秀博客: 鸿 ...

  3. 【Android】10.5 滚动视图(RecyclerView)

    分类:C#.Android.VS2015: 创建日期:2016-02-19 一.简介 滚动视图(RecyclerView)的用法与布局控件的用法类似,唯一不同的是,所有布局控件中都可以包含多个组件,而 ...

  4. RecyclerView 源码分析(二) —— 缓存机制

    在前一篇文章 RecyclerView 源码分析(一) -- 绘制流程解析 介绍了 RecyclerView 的绘制流程,RecyclerView 通过将绘制流程从 View 中抽取出来,放到 Lay ...

  5. 【腾讯Bugly干货分享】Android ListView与RecyclerView对比浅析--缓存机制

    本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/5811d3e3ab10c62013697408 作者:黄宁源 一,背景 Recy ...

  6. RecyclerView与ListView 对比浅析:缓存机制

    一. 背景 PS:相关知识:ListView与RecyclerView缓存机制原理大致相似,如下图所示: 滑动过程中,离屏的ItemView即被回收至缓存,入屏的ItemView则会优先从缓存中获取, ...

  7. ListView与RecyclerView对比浅析——缓存机制

    https://www.jianshu.com/p/193fb966e954 一,背景 RecyclerView是谷歌官方出的一个用于大量数据展示的新控件,可以用来代替传统的ListView,更加强大 ...

  8. [转]Android ListView 与 RecyclerView 对比浅析—缓存机制

    从源码角度剖析ListView 与 RecyclerView 缓存机制的不同 https://zhuanlan.zhihu.com/p/23339185 原文地址:http://dev.qq.com/ ...

  9. 【FastDev4Android框架开发】RecyclerView完全解析之下拉刷新与上拉加载SwipeRefreshLayout(三十一)

    转载请标明出处: http://blog.csdn.net/developer_jiangqq/article/details/49992269 本文出自:[江清清的博客] (一).前言: [好消息] ...

随机推荐

  1. 自己封装个ajax

    你是否发现项目中有很多页面只用到了框架不到十分之一的内容,还引了压缩后还有70多kb的jquery库 你是否发现项目中就用了两三个underscore提供的方法,其他大部分的你方法你甚至从来没有看过 ...

  2. atitit.错误:找不到或无法加载主类 的解决 v4 qa15.doc

    atitit.错误:找不到或无法加载主类 的解决 v4 qa15.doc 1.1. 修改此java文件,让他启动编译,还是不能生成了新的class, 1.2. 估计ide调试锁死class ,查看de ...

  3. iptables基础命令详解

    TCP/IP基本概念: TCP/IP将网络分为四层:应用层,传输层,网络层,链路层. 传输层:定义了两种通信协议,分别为TCP协议和UDP协议. TCP协议:TCP协议在传输 数据过程中会检查数据的完 ...

  4. Jenkins的插件管理(安装和更新插件)

    使用Jenkins的编译部署项目需要依赖各种插件 下面安装Jenkins的各种插件: 1.登录Jenkins进入以下界面: 2.点击 系统管理 : 3.点击 管理插件 : 4.点击 可选插件 选择你需 ...

  5. Linux下MakeFile初探

    make是linux下的编译命令,用于编译和生成Linux下的可执行文件.这个命令处理的对象是Makefile,makefile等.由于make的强大解析能力,makefile文件的编写也变得极为简单 ...

  6. 第四章 HTML与JavaScript

    DHTML就是与CSS和Web文档进行交互生成动态页面的JavaScript. 4.1HTML文档剖析 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML ...

  7. sublime text2小技巧

    1. 文件快速导航: 这是sublime上面很好用的功能之一,ctrl+p可以调出窗口,菜单上的解释是gotoanythings ,确实如其所言,调出窗口后,直接输入关键字,可以在已打开的项目文件夹中 ...

  8. Representation Data in OpenCascade BRep

    Representation Data in OpenCascade BRep eryar@163.com 摘要Abstract:现在的显示器大多数是光栅显示器,即可以看做一个像素的矩阵.在光栅显示器 ...

  9. ZOJ3805Machine(二叉树左右子树变换)

    /* 题意:建立一棵二叉树,左子树和父节点占一个宽度,右子树另外占一个宽度! 使任意左右子树交换顺序,使得整个树的宽度最小! 思路:递归交换左右子树 ! 开始写的代码复杂了,其实左右子树不用真的交换, ...

  10. python--基础学习(三)字符串单引号、双引号、三引号

    1.基本认识 单引号字符串:'python' 双引号字符串:"python" 三引号字符串:'''python'''(三单引号),"""python& ...