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

前言:上篇我们讲了怎么初步使用PullToRefresh,但上篇只是几个简单的字符串,在真正的项目中,不可能只是这么简单的,而是复杂的XML的累积,这篇我在前一篇和以前讲的simpleAdapter的基础上,进一步实现复杂XML的下拉刷新

相关文章:

(这篇文章是建立在这三篇文章的基础上,其实是在利用了《List控件使用--SimpleAdapter使用详解(二)》的布局和重写BaseAdapter的代码,然后利用了《PullToRefresh使用详解(一)--构建下拉刷新的ListView》的下拉刷新功能。所以文章的部分代码省略没讲,强烈建议大家先看这三篇。)

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

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

3、《PullToRefresh使用详解(一)--构建下拉刷新的ListView


其它相关文章

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

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

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

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


效果图:

                                   正在刷新                                                                     刷新后

      

一、XML代码

1、activity_main.xml

PullToRefresh标准写法,与《PullToRefresh使用详解(一)--构建下拉刷新的ListView》布局一样。

[html]  view plain  copy
  在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.   
  9.     <com.handmark.pulltorefresh.library.PullToRefreshListView  
  10.         android:id="@+id/pull_refresh_list"  
  11.         android:layout_width="fill_parent"  
  12.         android:layout_height="fill_parent"  
  13.         android:cacheColorHint="#00000000"  
  14.         android:divider="#19000000"  
  15.         android:dividerHeight="4dp"  
  16.         android:fadingEdge="none"  
  17.         android:fastScrollEnabled="false"  
  18.         android:footerDividersEnabled="false"  
  19.         android:headerDividersEnabled="false"  
  20.         android:smoothScrollbar="true" />  
  21.   
  22. </LinearLayout>  

2、数据项XML(item.xml)

与《List控件使用--SimpleAdapter使用详解(二)》布局一样,只是将名字改成了item.xml

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="horizontal" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.   
  6.     <ImageView android:id="@+id/img"   
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"   
  9.         android:layout_margin="5px"/>  
  10.   
  11.     <LinearLayout android:orientation="vertical"  
  12.         android:layout_width="wrap_content"   
  13.         android:layout_height="wrap_content">  
  14.   
  15.         <TextView android:id="@+id/name"   
  16.             android:layout_width="wrap_content"  
  17.             android:layout_height="wrap_content"   
  18.             android:textColor="#FFFFFF00"  
  19.             android:textSize="22px" />  
  20.         <TextView android:id="@+id/info"   
  21.             android:layout_width="wrap_content"  
  22.             android:layout_height="wrap_content"   
  23.             android:textColor="#FF00FFFF"  
  24.             android:textSize="13px" />  
  25.     </LinearLayout>  
  26.       
  27. </LinearLayout>  

二、JAVA代码

先贴出全部代码,然后再慢慢讲。

完整代码

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.example.try_pulltorefresh_map;  
  2. //try_PullToRefresh_map  
  3. /** 
  4.  * 完成了从TXT文本中提取,并向下刷新 
  5.  * blog:http://blog.csdn.net/harvic880925/article/details/17708409 
  6.  * @author harvic 
  7.  * @date  2013-12-31 
  8.  *  
  9.  */  
  10. import java.io.BufferedReader;  
  11. import java.io.IOException;  
  12. import java.io.InputStream;  
  13. import java.io.InputStreamReader;  
  14. import java.io.UnsupportedEncodingException;  
  15. import java.util.ArrayList;  
  16. import java.util.HashMap;  
  17. import org.json.JSONArray;  
  18.   
  19. import com.handmark.pulltorefresh.library.PullToRefreshBase;  
  20. import com.handmark.pulltorefresh.library.PullToRefreshListView;  
  21. import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;  
  22. import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;  
  23.   
  24. import android.os.AsyncTask;  
  25. import android.os.Bundle;  
  26. import android.app.ListActivity;  
  27. import android.content.Context;  
  28. import android.graphics.Bitmap;  
  29. import android.graphics.BitmapFactory;  
  30. import android.text.format.DateUtils;  
  31. import android.view.LayoutInflater;  
  32. import android.view.View;  
  33. import android.view.ViewGroup;  
  34. import android.widget.BaseAdapter;  
  35. import android.widget.ImageView;  
  36. import android.widget.ListView;  
  37. import android.widget.TextView;  
  38.   
  39. public class MainActivity extends ListActivity {  
  40.       
  41.     private ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();  
  42.     private PullToRefreshListView mPullRefreshListView;  
  43.     MyAdapter adapter=null;  
  44.   
  45.     @Override  
  46.     protected void onCreate(Bundle savedInstanceState) {  
  47.         super.onCreate(savedInstanceState);  
  48.         setContentView(R.layout.activity_main);  
  49.           
  50.         mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);  
  51.   
  52.         //设定下拉监听函数  
  53.         mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {  
  54.             @Override  
  55.             public void onRefresh(PullToRefreshBase<ListView> refreshView) {  
  56.                 String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),  
  57.                         DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);  
  58.   
  59.                 // Update the LastUpdatedLabel  
  60.                 refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);  
  61.   
  62.                 // Do work to refresh the list here.  
  63.                 new GetDataTask().execute();  
  64.             }  
  65.         });  
  66.   
  67.         mPullRefreshListView.setMode(Mode.PULL_FROM_END);//设置底部下拉刷新模式  
  68.           
  69.         listItem=getData();//获取LIST数据  
  70.         adapter = new MyAdapter(this);  
  71.   
  72.         //设置适配器  
  73.         ListView actualListView = mPullRefreshListView.getRefreshableView();  
  74.         actualListView.setAdapter(adapter);   
  75.           
  76.     }  
  77.     private class GetDataTask extends AsyncTask<Void, Void, HashMap<String, Object>> {  
  78.   
  79.         //后台处理部分  
  80.         @Override  
  81.         protected HashMap<String, Object> doInBackground(Void... params) {  
  82.             // Simulates a background job.  
  83.             try {  
  84.                 Thread.sleep(1000);  
  85.             } catch (InterruptedException e) {  
  86.             }  
  87.             HashMap<String, Object> map = new HashMap<String, Object>();  
  88.             try {  
  89.                   
  90.                 map = new HashMap<String, Object>();  
  91.                 map.put("name""林珊");  
  92.                 map.put("info""上传了一张新照片油画");  
  93.                 map.put("img","youhua");  
  94.                   
  95.             } catch (Exception e) {  
  96.                 // TODO: handle exception  
  97.                 setTitle("map出错了");  
  98.                 return null;  
  99.             }  
  100.               
  101.             return map;  
  102.         }  
  103.   
  104.         //这里是对刷新的响应,可以利用addFirst()和addLast()函数将新加的内容加到LISTView中  
  105.         //根据AsyncTask的原理,onPostExecute里的result的值就是doInBackground()的返回值  
  106.         @Override  
  107.         protected void onPostExecute(HashMap<String, Object> result) {  
  108.             //在头部增加新添内容  
  109.               
  110.             try {  
  111.                 listItem.add(result);  
  112.                   
  113.                 //通知程序数据集已经改变,如果不做通知,那么将不会刷新mListItems的集合  
  114.                 adapter.notifyDataSetChanged();  
  115.                 // Call onRefreshComplete when the list has been refreshed.  
  116.                 mPullRefreshListView.onRefreshComplete();  
  117.             } catch (Exception e) {  
  118.                 // TODO: handle exception  
  119.                 setTitle(e.getMessage());  
  120.             }  
  121.               
  122.   
  123.             super.onPostExecute(result);  
  124.         }  
  125.     }  
  126.       
  127.     private ArrayList<HashMap<String, Object>> getData() {  
  128.         ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();  
  129.         HashMap<String, Object> map = new HashMap<String, Object>();  
  130.         InputStream inputStream;  
  131.         try {  
  132.             inputStream=this.getAssets().open("my_home_friends.txt");  
  133.             String json=readTextFile(inputStream);  
  134.             JSONArray array = new JSONArray(json);  
  135.             for (int i = 0; i < array.length(); i++) {  
  136.                 map = new HashMap<String, Object>();  
  137.                 map.put("name", array.getJSONObject(i).getString("name"));  
  138.                 map.put("info", array.getJSONObject(i).getString("info"));  
  139.                 map.put("img",array.getJSONObject(i).getString("photo"));  
  140.                 list.add(map);  
  141.             }  
  142.             return list;      
  143.               
  144.         } catch (Exception e) {  
  145.             // TODO: handle exception  
  146.             e.printStackTrace();  
  147.         }  
  148.           
  149.           
  150.         return list;      
  151.     }  
  152.   
  153.       
  154.       
  155.     public final class ViewHolder{  
  156.         public ImageView img;  
  157.         public TextView name;  
  158.         public TextView info;  
  159.     }         
  160.       
  161.     public class MyAdapter extends BaseAdapter{  
  162.   
  163.         private LayoutInflater mInflater;  
  164.           
  165.         public MyAdapter(Context context){  
  166.             this.mInflater = LayoutInflater.from(context);  
  167.         }  
  168.         @Override  
  169.         public int getCount() {  
  170.             // TODO Auto-generated method stub  
  171.             return listItem.size();  
  172.         }  
  173.   
  174.         @Override  
  175.         public Object getItem(int arg0) {  
  176.             // TODO Auto-generated method stub  
  177.             return null;  
  178.         }  
  179.   
  180.         @Override  
  181.         public long getItemId(int arg0) {  
  182.             // TODO Auto-generated method stub  
  183.             return 0;  
  184.         }  
  185.           
  186.         @Override  
  187.         public View getView(int position, View convertView, ViewGroup parent) {  
  188.               
  189.             ViewHolder holder = null;  
  190.             if (convertView == null) {  
  191.                   
  192.                 holder=new ViewHolder();    
  193.                   
  194.                 convertView = mInflater.inflate(R.layout.item, null);  
  195.                 holder.img = (ImageView)convertView.findViewById(R.id.img);  
  196.                 holder.name = (TextView)convertView.findViewById(R.id.name);  
  197.                 holder.info = (TextView)convertView.findViewById(R.id.info);  
  198.                 convertView.setTag(holder);  
  199.                   
  200.             }else {  
  201.                   
  202.                 holder = (ViewHolder)convertView.getTag();  
  203.             }  
  204.               
  205.             holder.img.setImageBitmap(getHome((String)listItem.get(position).get("img")));  
  206.             holder.name.setText((String)listItem.get(position).get("name"));  
  207.             holder.info.setText((String)listItem.get(position).get("info"));  
  208.   
  209.             return convertView;  
  210.         }  
  211.           
  212.     }  
  213.       
  214.       
  215.     /** 
  216.      * 根据图片名称获取主页图片 
  217.      */  
  218.     public Bitmap getHome(String photo){          
  219.         String homeName = photo + ".jpg";  
  220.         InputStream is=null;  
  221.           
  222.         try {  
  223.             is=getAssets().open("home/"+homeName);  
  224.             Bitmap bitmap = BitmapFactory.decodeStream(is);       
  225.             is.close();  
  226.             return bitmap;  
  227.         } catch (Exception e) {  
  228.             e.printStackTrace();  
  229.         }  
  230.          
  231.         return null;  
  232.   
  233.     }  
  234.       
  235.     工具类  
  236.     /** 
  237.      *  
  238.      * @param inputStream 
  239.      * @return 
  240.      */  
  241.     public String readTextFile(InputStream inputStream) {  
  242.         String readedStr = "";  
  243.         BufferedReader br;  
  244.         try {  
  245.             br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
  246.             String tmp;  
  247.             while ((tmp = br.readLine()) != null) {  
  248.                 readedStr += tmp;  
  249.             }  
  250.             br.close();  
  251.             inputStream.close();  
  252.         } catch (UnsupportedEncodingException e) {  
  253.             e.printStackTrace();  
  254.         } catch (IOException e) {  
  255.             e.printStackTrace();  
  256.         }  
  257.   
  258.         return readedStr;  
  259.     }  
  260.   
  261.   
  262. }  
讲解:

执行流程:
看起来代码挺长,其实只看OnCreate()函数就能知道,只是分成了几大块,先贴出OnCreate()函数

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2. protected void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.     setContentView(R.layout.activity_main);  
  5.       
  6.     mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);  
  7.   
  8.     //设定下拉监听函数  
  9.     mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {  
  10.         @Override  
  11.         public void onRefresh(PullToRefreshBase<ListView> refreshView) {  
  12.             String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),  
  13.                     DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);  
  14.   
  15.             // Update the LastUpdatedLabel  
  16.             refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);  
  17.   
  18.             // Do work to refresh the list here.  
  19.             new GetDataTask().execute();  
  20.         }  
  21.     });  
  22.   
  23.     mPullRefreshListView.setMode(Mode.PULL_FROM_END);//设置底部下拉刷新模式  
  24.       
  25.     listItem=getData();//获取LIST数据  
  26.     adapter = new MyAdapter(this);  
  27.   
  28.     //设置适配器  
  29.     ListView actualListView = mPullRefreshListView.getRefreshableView();  
  30.     actualListView.setAdapter(adapter);   
  31.       
  32. }  

1、首先初始化mPullRefreshListView,然后设定监听函数,监听函数没变,我只是更改了GetDataTask()函数里的部分代码,我相信大家也能看懂,难度不大;

2、设定下拉模式,绑定适配器,对应代码

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. mPullRefreshListView.setMode(Mode.PULL_FROM_END);//设置底部下拉刷新模式  
  2.   
  3. listItem=getData();//获取LIST数据  
  4. adapter = new MyAdapter(this);  
  5.   
  6. //设置适配器  
  7. ListView actualListView = mPullRefreshListView.getRefreshableView();  
  8. actualListView.setAdapter(adapter);   
而这里的适配器是经过重写的,新生成了一个类MyAdapter extends BaseAdapter,关于重写适配器的方法,参考《List控件使用--SimpleAdapter使用详解(二)》;

到这就结束了,由于这篇文章是几篇文章的功能整合,很多东西相关的三篇文章都已经讲过了,也就没必要再讲,所以这里讲的比较粗略。


源码地址:http://download.csdn.net/detail/harvic880925/6790941 (不要分,仅供分享)


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


我个人的理解总结:

其实现思路跟上一篇几乎一样:

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

http://blog.csdn.net/qq_31753145/article/details/50930012

三个要点:

1.数据源

2.模板【这个例子是自己写的模板item.xml【自定义adapter】】+显示视图【PullToRefreshListView

3.适配器


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值