加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 00:27:34 所属栏目:百科 来源:网络整理
导读:?? 前言:上篇我们讲了怎么初步使用PullToRefresh,但上篇只是几个简单的字符串,在真正的项目中,不可能只是这么简单的,而是复杂的XML的累积,这篇我在前一篇和以前讲的simpleAdapter的基础上,进一步实现复杂XML的下拉刷新 相关文章: (这篇文章是建立在
??

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

相关文章:

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

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

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

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

效果图:

正在刷新 刷新后


一、XML代码

1、activity_main.xml

PullToRefresh标准写法,与《PullToRefresh使用详解(一)--构建下拉刷新的ListView》布局一样。
[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns: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. <!--ThePullToRefreshListViewreplacesastandardListViewwidget.-->
  7. <com.handmark.pulltorefresh.library.PullToRefreshListView
  8. android:id="@+id/pull_refresh_list"
  9. android:layout_width="fill_parent"
  10. android:layout_height="fill_parent"
  11. android:cacheColorHint="#00000000"
  12. android:divider="#19000000"
  13. android:dividerHeight="4dp"
  14. android:fadingEdge="none"
  15. android:fastScrollEnabled="false"
  16. android:footerDividersEnabled="false"
  17. android:headerDividersEnabled="false"
  18. android:smoothScrollbar="true"/>
  19. </LinearLayout>

2、数据项XML(item.xml)

与《List控件使用--SimpleAdapter使用详解(二)》布局一样,只是将名字改成了item.xml
[html] view plain copy print ?
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="horizontal"android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <ImageViewandroid:id="@+id/img"
  6. android:layout_width="wrap_content"
  7. android:layout_height="wrap_content"
  8. android:layout_margin="5px"/>
  9. <LinearLayoutandroid:orientation="vertical"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content">
  12. <TextViewandroid:id="@+id/name"
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:textColor="#FFFFFF00"
  16. android:textSize="22px"/>
  17. <TextViewandroid:id="@+id/info"
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:textColor="#FF00FFFF"
  21. android:textSize="13px"/>
  22. </LinearLayout>
  23. </LinearLayout>

二、JAVA代码

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

完整代码

[java] view plain copy print ?
  1. packagecom.example.try_pulltorefresh_map;
  2. //try_PullToRefresh_map
  3. /**
  4. *完成了从TXT文本中提取,并向下刷新
  5. *blog:http://blog.csdn.net/harvic880925/article/details/17708409
  6. *@authorharvic
  7. *@date2013-12-31
  8. *
  9. */
  10. importjava.io.BufferedReader;
  11. importjava.io.IOException;
  12. importjava.io.InputStream;
  13. importjava.io.InputStreamReader;
  14. importjava.io.UnsupportedEncodingException;
  15. importjava.util.ArrayList;
  16. importjava.util.HashMap;
  17. importorg.json.JSONArray;
  18. importcom.handmark.pulltorefresh.library.PullToRefreshBase;
  19. importcom.handmark.pulltorefresh.library.PullToRefreshListView;
  20. importcom.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
  21. importcom.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
  22. importandroid.os.AsyncTask;
  23. importandroid.os.Bundle;
  24. importandroid.app.ListActivity;
  25. importandroid.content.Context;
  26. importandroid.graphics.Bitmap;
  27. importandroid.graphics.BitmapFactory;
  28. importandroid.text.format.DateUtils;
  29. importandroid.view.LayoutInflater;
  30. importandroid.view.View;
  31. importandroid.view.ViewGroup;
  32. importandroid.widget.BaseAdapter;
  33. importandroid.widget.ImageView;
  34. importandroid.widget.ListView;
  35. importandroid.widget.TextView;
  36. publicclassMainActivityextendsListActivity{
  37. privateArrayList<HashMap<String,Object>>listItem=newArrayList<HashMap<String,Object>>();
  38. privatePullToRefreshListViewmPullRefreshListView;
  39. MyAdapteradapter=null;
  40. @Override
  41. protectedvoidonCreate(BundlesavedInstanceState){
  42. super.onCreate(savedInstanceState);
  43. setContentView(R.layout.activity_main);
  44. mPullRefreshListView=(PullToRefreshListView)findViewById(R.id.pull_refresh_list);
  45. //设定下拉监听函数
  46. mPullRefreshListView.setOnRefreshListener(newOnRefreshListener<ListView>(){
  47. @Override
  48. publicvoidonRefresh(PullToRefreshBase<ListView>refreshView){
  49. Stringlabel=DateUtils.formatDateTime(getApplicationContext(),System.currentTimeMillis(),
  50. DateUtils.FORMAT_SHOW_TIME|DateUtils.FORMAT_SHOW_DATE|DateUtils.FORMAT_ABBREV_ALL);
  51. //UpdatetheLastUpdatedLabel
  52. refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
  53. //Doworktorefreshthelisthere.
  54. newGetDataTask().execute();
  55. }
  56. });
  57. mPullRefreshListView.setMode(Mode.PULL_FROM_END);//设置底部下拉刷新模式
  58. listItem=getData();//获取LIST数据
  59. adapter=newMyAdapter(this);
  60. //设置适配器
  61. ListViewactualListView=mPullRefreshListView.getRefreshableView();
  62. actualListView.setAdapter(adapter);
  63. }
  64. privateclassGetDataTaskextendsAsyncTask<Void,Void,HashMap<String,Object>>{
  65. //后台处理部分
  66. @Override
  67. protectedHashMap<String,Object>doInBackground(Void...params){
  68. //Simulatesabackgroundjob.
  69. try{
  70. Thread.sleep(1000);
  71. }catch(InterruptedExceptione){
  72. }
  73. HashMap<String,Object>map=newHashMap<String,Object>();
  74. try{
  75. map=newHashMap<String,Object>();
  76. map.put("name","林珊");
  77. map.put("info","上传了一张新照片油画");
  78. map.put("img","youhua");
  79. }catch(Exceptione){
  80. //TODO:handleexception
  81. setTitle("map出错了");
  82. returnnull;
  83. }
  84. returnmap;
  85. }
  86. //这里是对刷新的响应,可以利用addFirst()和addLast()函数将新加的内容加到LISTView中
  87. //根据AsyncTask的原理,onPostExecute里的result的值就是doInBackground()的返回值
  88. @Override
  89. protectedvoidonPostExecute(HashMap<String,Object>result){
  90. //在头部增加新添内容
  91. try{
  92. listItem.add(result);
  93. //通知程序数据集已经改变,如果不做通知,那么将不会刷新mListItems的集合
  94. adapter.notifyDataSetChanged();
  95. //CallonRefreshCompletewhenthelisthasbeenrefreshed.
  96. mPullRefreshListView.onRefreshComplete();
  97. }catch(Exceptione){
  98. //TODO:handleexception
  99. setTitle(e.getMessage());
  100. }
  101. super.onPostExecute(result);
  102. }
  103. }
  104. privateArrayList<HashMap<String,Object>>getData(){
  105. ArrayList<HashMap<String,Object>>list=newArrayList<HashMap<String,Object>>();
  106. HashMap<String,Object>();
  107. InputStreaminputStream;
  108. try{
  109. inputStream=this.getAssets().open("my_home_friends.txt");
  110. Stringjson=readTextFile(inputStream);
  111. JSONArrayarray=newJSONArray(json);
  112. for(inti=0;i<array.length();i++){
  113. map=newHashMap<String,array.getJSONObject(i).getString("name"));
  114. map.put("info",array.getJSONObject(i).getString("info"));
  115. map.put("img",array.getJSONObject(i).getString("photo"));
  116. list.add(map);
  117. }
  118. returnlist;
  119. }catch(Exceptione){
  120. //TODO:handleexception
  121. e.printStackTrace();
  122. }
  123. returnlist;
  124. }
  125. publicfinalclassViewHolder{
  126. publicImageViewimg;
  127. publicTextViewname;
  128. publicTextViewinfo;
  129. }
  130. publicclassMyAdapterextendsBaseAdapter{
  131. privateLayoutInflatermInflater;
  132. publicMyAdapter(Contextcontext){
  133. this.mInflater=LayoutInflater.from(context);
  134. }
  135. @Override
  136. publicintgetCount(){
  137. //TODOAuto-generatedmethodstub
  138. returnlistItem.size();
  139. }
  140. @Override
  141. publicObjectgetItem(intarg0){
  142. //TODOAuto-generatedmethodstub
  143. returnnull;
  144. }
  145. @Override
  146. publiclonggetItemId(intarg0){
  147. //TODOAuto-generatedmethodstub
  148. return0;
  149. }
  150. @Override
  151. publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
  152. ViewHolderholder=null;
  153. if(convertView==null){
  154. holder=newViewHolder();
  155. convertView=mInflater.inflate(R.layout.item,null);
  156. holder.img=(ImageView)convertView.findViewById(R.id.img);
  157. holder.name=(TextView)convertView.findViewById(R.id.name);
  158. holder.info=(TextView)convertView.findViewById(R.id.info);
  159. convertView.setTag(holder);
  160. }else{
  161. holder=(ViewHolder)convertView.getTag();
  162. }
  163. holder.img.setImageBitmap(getHome((String)listItem.get(position).get("img")));
  164. holder.name.setText((String)listItem.get(position).get("name"));
  165. holder.info.setText((String)listItem.get(position).get("info"));
  166. returnconvertView;
  167. }
  168. }
  169. /**
  170. *根据图片名称获取主页图片
  171. */
  172. publicBitmapgetHome(Stringphoto){
  173. StringhomeName=photo+".jpg";
  174. InputStreamis=null;
  175. try{
  176. is=getAssets().open("home/"+homeName);
  177. Bitmapbitmap=BitmapFactory.decodeStream(is);
  178. is.close();
  179. returnbitmap;
  180. }catch(Exceptione){
  181. e.printStackTrace();
  182. }
  183. returnnull;
  184. }
  185. ////工具类
  186. /**
  187. *
  188. *@paraminputStream
  189. *@return
  190. */
  191. publicStringreadTextFile(InputStreaminputStream){
  192. StringreadedStr="";
  193. BufferedReaderbr;
  194. try{
  195. br=newBufferedReader(newInputStreamReader(inputStream,"UTF-8"));
  196. Stringtmp;
  197. while((tmp=br.readLine())!=null){
  198. readedStr+=tmp;
  199. }
  200. br.close();
  201. inputStream.close();
  202. }catch(UnsupportedEncodingExceptione){
  203. e.printStackTrace();
  204. }catch(IOExceptione){
  205. e.printStackTrace();
  206. }
  207. returnreadedStr;
  208. }
  209. }
讲解:

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

[java] view plain copy print ?
  1. @Override
  2. protectedvoidonCreate(BundlesavedInstanceState){
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_main);
  5. mPullRefreshListView=(PullToRefreshListView)findViewById(R.id.pull_refresh_list);
  6. //设定下拉监听函数
  7. mPullRefreshListView.setOnRefreshListener(newOnRefreshListener<ListView>(){
  8. @Override
  9. publicvoidonRefresh(PullToRefreshBase<ListView>refreshView){
  10. Stringlabel=DateUtils.formatDateTime(getApplicationContext(),
  11. DateUtils.FORMAT_SHOW_TIME|DateUtils.FORMAT_SHOW_DATE|DateUtils.FORMAT_ABBREV_ALL);
  12. //UpdatetheLastUpdatedLabel
  13. refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
  14. //Doworktorefreshthelisthere.
  15. newGetDataTask().execute();
  16. }
  17. });
  18. mPullRefreshListView.setMode(Mode.PULL_FROM_END);//设置底部下拉刷新模式
  19. listItem=getData();//获取LIST数据
  20. adapter=newMyAdapter(this);
  21. //设置适配器
  22. ListViewactualListView=mPullRefreshListView.getRefreshableView();
  23. actualListView.setAdapter(adapter);
  24. }

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

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

[java] view plain copy print ?
  1. mPullRefreshListView.setMode(Mode.PULL_FROM_END);//设置底部下拉刷新模式
  2. listItem=getData();//获取LIST数据
  3. adapter=newMyAdapter(this);
  4. //设置适配器
  5. ListViewactualListView=mPullRefreshListView.getRefreshableView();
  6. actualListView.setAdapter(adapter);
而这里的适配器是经过重写的,新生成了一个类MyAdapterextends BaseAdapter,关于重写适配器的方法,参考《List控件使用--SimpleAdapter使用详解(二)》;

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


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


请大家尊重原创者版权,转载请标明出处:http://www.52php.cn/article/p-eqxnrlgc-bae.html,谢谢!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读