PullToRefresh使用详解(一)--构建下拉刷新的listView

前言:前几天写了篇关于PullToRefresh控件的DEMO导入的博客,但由于当时没有用到,所以就没细往下讲,现在开始到了实战阶段,用到了PullToRefresh的listView样式,网上有讲的,但讲的不多,而且没有详细的例子来说,下面我讲讲这个东东的实现方法。这个例子对应PullToRefreshDemo里的第一个选项ListView;

注意:本篇仅写的如何实现下拉刷新,对于上拉加载的问题,参见《使用PullToRefresh实现下拉刷新和上拉加载》

相关文章:

1、《List控件使用--SimpleAdapter使用详解(一)

2、《List控件使用--SimpleAdapter使用详解(二)

3、《PullToRefresh使用详解(二)---重写BaseAdapter实现复杂XML下拉刷新》

4、《PullToRefresh使用详解(三)--实现异步加载的下拉刷新列表》

5、《PullToRefresh使用详解(四)--利用回调函数实现到底加载》

6、《PullToRefresh使用详解(五)--下拉刷新的ScrollView》

效果图: 

                               正在刷新                                                                       刷新后

      

一、导入Library

下载源码后(https://github.com/chrisbanes/Android-PullToRefresh),里面有个Library工程,添加工程到Eclipse中;

另外extras文件夹还有两个工程:PullToRefreshListFragment和PullToRefreshViewPager,由于我们的这个用不到他们的库文件,所以不必导入了;

二、实战

1、新建工程,添加Libray库到工程中

新建工程(try_PullToRefresh)后,右键-》Properties-》Android-》Add  选择上面的Library,然后就是这个样子的

2、重写activity_main.xml

XML内容为:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.       
  7. <!--     The PullToRefreshListView replaces a standard ListView widget. -->  
  8.     <com.handmark.pulltorefresh.library.PullToRefreshListView  
  9.         android:id="@+id/pull_refresh_list"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="fill_parent"  
  12.         android:cacheColorHint="#00000000"  
  13.         android:divider="#19000000"  
  14.         android:dividerHeight="4dp"  
  15.         android:fadingEdge="none"  
  16.         android:fastScrollEnabled="false"  
  17.         android:footerDividersEnabled="false"  
  18.         android:headerDividersEnabled="false"  
  19.         android:smoothScrollbar="true" />  
  20.   
  21. </LinearLayout>  

其中中间那一大段<com.handmark.pull………………/>就是相当于ListView控件,用这段来代替原是ListView控件的代码

3、JAVA代码讲解

全部代码:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. package com.example.try_pulltorefresh;  
  2.   
  3. import java.util.Arrays;  
  4. import java.util.LinkedList;  
  5.   
  6. import com.handmark.pulltorefresh.library.PullToRefreshBase;  
  7. import com.handmark.pulltorefresh.library.PullToRefreshListView;  
  8. import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;  
  9.   
  10. import android.os.AsyncTask;  
  11. import android.os.Bundle;  
  12. import android.app.Activity;  
  13. import android.text.format.DateUtils;  
  14. import android.widget.ArrayAdapter;  
  15. import android.widget.ListView;  
  16.   
  17. public class MainActivity extends Activity {  
  18.     private String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",  
  19.             "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",  
  20.             "Allgauer Emmentaler", "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",  
  21.             "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",  
  22.             "Allgauer Emmentaler" };  
  23.     private LinkedList<String> mListItems;  
  24.     private PullToRefreshListView mPullRefreshListView;  
  25.     private ArrayAdapter<String> mAdapter;  
  26.   
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.activity_main);  
  31.           
  32.         mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);  
  33.   
  34.         // Set a listener to be invoked when the list should be refreshed.  
  35.         mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {  
  36.             @Override  
  37.             public void onRefresh(PullToRefreshBase<ListView> refreshView) {  
  38.                 String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),  
  39.                         DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);  
  40.   
  41.                 // Update the LastUpdatedLabel  
  42.                 refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);  
  43.   
  44.                 // Do work to refresh the list here.  
  45.                 new GetDataTask().execute();  
  46.             }  
  47.         });  
  48.   
  49.         mListItems = new LinkedList<String>();  
  50.         mListItems.addAll(Arrays.asList(mStrings));  
  51.   
  52.         mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);  
  53.   
  54.         //这两个绑定方法用其一  
  55.         // 方法一  
  56. //       mPullRefreshListView.setAdapter(mAdapter);  
  57.         //方法二  
  58.         ListView actualListView = mPullRefreshListView.getRefreshableView();  
  59.         actualListView.setAdapter(mAdapter);  
  60.     }  
  61.   
  62.     private class GetDataTask extends AsyncTask<Void, Void, String> {  
  63.   
  64.         //后台处理部分  
  65.         @Override  
  66.         protected String doInBackground(Void... params) {  
  67.             // Simulates a background job.  
  68.             try {  
  69.                 Thread.sleep(1000);  
  70.             } catch (InterruptedException e) {  
  71.             }  
  72.             String str="Added after refresh...I add";  
  73.             return str;  
  74.         }  
  75.   
  76.         //这里是对刷新的响应,可以利用addFirst()和addLast()函数将新加的内容加到LISTView中  
  77.         //根据AsyncTask的原理,onPostExecute里的result的值就是doInBackground()的返回值  
  78.         @Override  
  79.         protected void onPostExecute(String result) {  
  80.             //在头部增加新添内容  
  81.             mListItems.addFirst(result);  
  82.               
  83.             //通知程序数据集已经改变,如果不做通知,那么将不会刷新mListItems的集合  
  84.             mAdapter.notifyDataSetChanged();  
  85.             // Call onRefreshComplete when the list has been refreshed.  
  86.             mPullRefreshListView.onRefreshComplete();  
  87.   
  88.             super.onPostExecute(result);  
  89.         }  
  90.     }  
  91. }  

代码讲解:
1、变量定义

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. private LinkedList<String> mListItems;    //显示的列表对应原字符串  
  2. private PullToRefreshListView mPullRefreshListView;  //PullToRefreshListView实例  
  3. private ArrayAdapter<String> mAdapter;  //ListView的适配器  

2、在OnCreate()中主要分为两步
(1)初始化mPullRefreshListView并设置监听器,以执行当需要刷新时,应该怎么办,至于真正执行刷新的类GetDataTask()我们后面再细讲,对应代码为:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);  
  2.   
  3. // Set a listener to be invoked when the list should be refreshed.  
  4. mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {  
  5.     @Override  
  6.     public void onRefresh(PullToRefreshBase<ListView> refreshView) {  
  7.         String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),  
  8.                 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);  
  9.   
  10.         // Update the LastUpdatedLabel  
  11.         refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);  
  12.   
  13.         // Do work to refresh the list here.  
  14.         new GetDataTask().execute();  
  15.     }  
  16. });  

(2)设置适配器列表内容,并与ListView绑定以显示出来,对应代码为:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. //设置列表内容  
  2. mListItems = new LinkedList<String>();  
  3. mListItems.addAll(Arrays.asList(mStrings));  
  4. mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);  
  5.   
  6. //这两个绑定方法用其一  
  7. // 方法一  
  8. //       mPullRefreshListView.setAdapter(mAdapter);  
  9. //方法二  
  10. ListView actualListView = mPullRefreshListView.getRefreshableView();  
  11. actualListView.setAdapter(mAdapter);  

3、执行刷新的类GetDataTask()
先贴出这段代码来:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. private class GetDataTask extends AsyncTask<Void, Void, String> {//定义返回值的类型  
  2.     // 后台处理部分  
  3.     @Override  
  4.     protected String doInBackground(Void... params) {  
  5.         // Simulates a background job.  
  6.         try {  
  7.             Thread.sleep(1000);  
  8.         } catch (InterruptedException e) {  
  9.         }  
  10.         String str="Added after refresh...I add";  
  11.         return str;  
  12.     }  
  13.   
  14.     //这里是对刷新的响应,可以利用addFirst()和addLast()函数将新加的内容加到LISTView中  
  15.     //根据AsyncTask的原理,onPostExecute里的result的值就是doInBackground()的返回值  
  16.     @Override  
  17.     protected void onPostExecute(String result) {  
  18.         //在头部增加新添内容  
  19.         mListItems.addFirst(result);  
  20.           
  21.         //通知程序数据集已经改变,如果不做通知,那么将不会刷新mListItems的集合  
  22.         mAdapter.notifyDataSetChanged();  
  23.         // Call onRefreshComplete when the list has been refreshed.  
  24.         mPullRefreshListView.onRefreshComplete();  
  25.   
  26.         super.onPostExecute(result);//这句是必有的,AsyncTask规定的格式  
  27.     }  
  28. }  
(1)派生自AsyncTask

由于派生自AsyncTask,所以下面的那个函数doInBackground和onPostExecute就不难理解了,这两个函数是AsyncTask必须是重写的两个函数
(2)doInBackground函数

doInBackground执行要于后台执行的语句,返回的值可以是任意类型,但要提前在extends AsyncTask<Void, Void, String> 中定义,这个返回值会做为onPostExecute的参数result传到onPostExecute函数中;如果对于网络访问程序,doInBackground就执行访问网络的代码,然后讲返回值存在result中传给onPostExecute函数,以刷新列表;

 (3)onPostExecute函数

 onPostExecute()是对返回的值进行操作,并添加到ListView的列表中,有两种添加方式添加到头部----mListItems.addFirst(result);和添加在尾部----mListItems.addLast(result);

至于 AsyncTask,下面是几个网页,讲的还可以,大家可以参考下:

 《android AsyncTask 详解》:http://www.eoeandroid.com/thread-168004-1-1.html

 《android AsyncTask 详解》(同名):http://blog.csdn.net/dabizime/article/details/6695705

《android之AsyncTask》:http://blog.csdn.net/singwhatiwanna/article/details/9272195 

《Android源码分析--带你认识不一样的AsyncTask》:http://blog.csdn.net/singwhatiwanna/article/details/17596225 (绝对精品)

 另外:

 1、设置向上拉刷新还是向下拉刷新的代码:

 mPullRefreshListView.setMode(Mode.PULL_FROM_END);//向下拉刷新

 mPullRefreshListView.setMode(Mode.PULL_FROM_START);//向上拉刷新

mPullRefreshListView.setMode(Mode.BOTH);//两端刷新
 

注意:这只是一个精简版,在源码中还有一些可借签的代码,可以在看懂这个以后,可以回过头来再看看源码,我相信肯定会有收获的。

源码来啦:http://download.csdn.net/detail/harvic880925/6788247(不要分,仅供分享)

 

请大家尊重原创者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/17680305

版权声明:本文为博主原创文章,未经博主允许不得转载。

 
原文地址:https://www.cnblogs.com/xgjblog/p/4608251.html