仿知乎程序(三)读取webService,解析json,volley以及PullToRefreshListView的使用

来源:互联网 发布:p2p网络运营招聘 编辑:程序博客网 时间:2024/06/05 11:52

       我们已经实现了侧滑菜单的切换与toolbar菜单根据不同页面显示不同工具的功能,今天我们就来完成首页的显示。知乎首页有这么几个功能:

1,列表功能,信息是以列表的形式展示出来的
2,列表要能实现下拉刷新,上拉加载的功能
3,图片与文字并存
4,点击其中一项的不同区域,会跳到不同的详细页面,点击标题会跳动到一个页面,点击下面信息概要又会跳到另一个页面

     好,我们就来实现这四个功能。
     这里的信息,我是通过读取服务器上webService传过来的json数据,进行解析来当信息源的。所以我们先要把信息源从服务器读出来,才能进行下面的操作。在做这之前,我们先看一下这个首页都有哪些项,有一个用户的图片,一个标题,一个信息的大小,和信息的内容。为了能更好的进行将信息读取,我们先建一个model类,把相关的字段先加上。代码如下:

IndexList.Java

[java] view plain copy
  1. /** 
  2.  * 用于显示在index_fragment中ListView的内容 
  3.  * Created by cg on 2015/10/29. 
  4.  */  
  5. public class IndexList {  
  6.     private int questionID;                                                  //问题ID  
  7.     private String questionTitle;                                            //问题标题  
  8.     private String questionSize;                                             //问题点在字节数  
  9.     private String questionContent;                                          //问题内容  
  10.     private String userPic;                                                  //发问者头像  
  11.   
  12.     public IndexList() {  
  13.     }  
  14.   
  15.     public IndexList(int questionID, String questionTitle, String questionSize, String questionContent, String userPic) {  
  16.         this.questionID = questionID;  
  17.         this.questionTitle = questionTitle;  
  18.         this.questionSize = questionSize;  
  19.         this.questionContent = questionContent;  
  20.         this.userPic = userPic;  
  21.     }  
  22.   
  23.     public int getQuestionID() {  
  24.         return questionID;  
  25.     }  
  26.   
  27.     public void setQuestionID(int questionID) {  
  28.         this.questionID = questionID;  
  29.     }  
  30.   
  31.     public String getQuestionTitle() {  
  32.         return questionTitle;  
  33.     }  
  34.   
  35.     public void setQuestionTitle(String questionTitle) {  
  36.         this.questionTitle = questionTitle;  
  37.     }  
  38.   
  39.     public String getQuestionSize() {  
  40.         return questionSize;  
  41.     }  
  42.   
  43.     public void setQuestionSize(String questionSize) {  
  44.         this.questionSize = questionSize;  
  45.     }  
  46.   
  47.     public String getQuestionContent() {  
  48.         return questionContent;  
  49.     }  
  50.   
  51.     public void setQuestionContent(String questionContent) {  
  52.         this.questionContent = questionContent;  
  53.     }  
  54.   
  55.     public String getUserPic() {  
  56.         return userPic;  
  57.     }  
  58.   
  59.     public void setUserPic(String userPic) {  
  60.         this.userPic = userPic;  
  61.     }  
  62. }  

       好,model类我们建好了,现在我们就要从webServies开始取数据了,android读取webServies有很多好的第三方插件,这里我使用的是Ksoap2-android,它的使用网上有很多,我就不多说了,https://github.com/simpligility/ksoap2-android可以去下载,下载之后,我们引入jar.因为这里面我们需要一些常用的变量值,比如说地址什么的,所以我使用一个class,来存这些常用变量
configStatic.java
[java] view plain copy
  1. /** 
  2.  * 常量信息 
  3.  * Created by cg on 2015/10/29. 
  4.  */  
  5. public class configStatic {  
  6.     /** 
  7.      * webServies地址的命名空间,域名 
  8.      */  
  9.     public static String WEBSERVIESNAMESPACE = "http://tempuri.org/";  
  10.   
  11.     /** 
  12.      * webServies明确地址 
  13.      */  
  14.     public static String WEBSERVIESURL = "http://192.168.0.163:8090/webServices/questionInfo.asmx";  
  15.   
  16.     /** 
  17.      *  webServices的方法名_用来提取10条问题 
  18.      */  
  19.     public static String WEBSERVICES_INDEXLIST = "getQuestionList";  
  20. }  

    这里的地址是我本地的地址,下面是它传回来的数据格式:
[html] view plain copy
  1. [{"questionID":28,"questionTitle":"苍井空老师的个人简介","questionSize":"387","questionContent":"\r\n 苍井空,1983年11月11日出生于日本东京。日本AV女演员、  
  2. 成人模特,兼电视、电影演员。日本女子组合惠比寿麝香葡萄的初代首领,现成员、OG首领。2010年3月毕业并将组合首领之位交托给麻美由真,同年10月复归。  
  3. \r\n 入行前曾是泳装写真女星,2002年进入AliceJapan公司,开始性感影片的拍摄生涯。因为其“童颜巨乳”的特色,开始获得人气,并连续在2003年及2004年蝉联日本  
  4. 《VideoBoy》杂志年度性感女艺人第一名。[1] 从2003年起,开始参加一般电视戏剧及综艺节目中演出,[2] 2004年11月移籍到S1,成功转型,大牌杂志模特及电影演员。  
  5. \r\n","userPic":"http://imgcdn.kdnet.net/UploadSmall/2013/07/21/137438445351976.jpg"},{"questionID":27,"questionTitle":"波多野结衣的故事",  
  6. "questionSize":"679","questionContent":"波多野结衣(はたの ゆい),女,1988年5月24日出生于日本京都府,著名日本女演员、AV女优。  
  7. 2008年,波多野结衣开始从事AV出演,并于11月加入H.M.P公司,成为H.M.P的素人,不久便被H.M.P公司雪藏,随后在BeFree公司发行过两部影片,  
  8. 又转投ATTACKER公司,后又签约SKY HIGH公司。2012年,波多野结衣出席第九届上海国际成人展开幕和第二届台湾成人博览会。",  
  9. "userPic":"http://img1.imgtn.bdimg.com/it/u=1823077414,3028399801\u0026fm=21\u0026gp=0.jpg"}]  
好,我们来看一下,如何读取这个webService:webservicesUntils.java
[java] view plain copy
  1. import org.ksoap2.SoapEnvelope;  
  2. import org.ksoap2.serialization.SoapObject;  
  3. import org.ksoap2.serialization.SoapSerializationEnvelope;  
  4. import org.ksoap2.transport.HttpTransportSE;  
  5. import org.xmlpull.v1.XmlPullParserException;  
  6.   
  7. import java.io.IOException;  
  8.   
  9. /** 
  10.  * webservice 操作类 
  11.  * Created by cg on 2015/10/29. 
  12.  */  
  13. public class webservicesUntils {  
  14.     private static SoapObject rpc = null;  
  15.     private static SoapSerializationEnvelope envelope = null;  
  16.     private static HttpTransportSE ht = null;  
  17.   
  18.     /** 
  19.      * 调用问题信息 
  20.      * @param strWhere      查询条件 
  21.      * @param orderby       排序字段 
  22.      * @param startIndex    开始记录数 
  23.      * @param endIndex      结束记录数 
  24.      * @return 
  25.      * @throws Exception 
  26.      */  
  27.     public static String getIndexItemList(final String strWhere,final String orderby,final int startIndex,final int endIndex) throws IOException, XmlPullParserException, IOException, XmlPullParserException {  
  28.   
  29.         rpc = new SoapObject(configStatic.WEBSERVIESNAMESPACE, configStatic.WEBSERVICES_INDEXLIST);  
  30.         // 设置调用方法参数的值  
  31.         rpc.addProperty("strWhere", strWhere);  
  32.         rpc.addProperty("orderby", orderby);  
  33.         rpc.addProperty("startIndex", startIndex);  
  34.         rpc.addProperty("endIndex",endIndex);  
  35.   
  36.         // 生成调用Webservice方法的SOAP请求信息  
  37.         envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);         //这里要注意,这里是webService的版本号,一般是10,11,12这三个值,如果你不确定,可以每个都试一下  
  38.         envelope.bodyOut = rpc;  
  39.         envelope.dotNet = true;  
  40.         envelope.setOutputSoapObject(rpc);  
  41.         // 创建HttpTransportSE对象,通过HttpTransportSE类的构造方法可以指定WebService的url  
  42.         ht = new HttpTransportSE(configStatic.WEBSERVIESURL);  
  43.         ht.debug = true;  
  44.         // 使用call方法调用WebService方法  
  45.   
  46.         ht.call(null, envelope);  
  47.   
  48.         String result = "0";  
  49.   
  50.         //检查ht.call是否运行  
  51.         //Log.e("city", strWhere + startIndex + endIndex);  
  52.   
  53.         // 判断取到的值是否为空  
  54.         if(envelope.getResponse() == null) {  
  55.             result = "0";  
  56.         }else{  
  57.             result = envelope.getResponse().toString();  
  58.         }  
  59.   
  60.         return result;  
  61.     }  
  62. }  
要想让它好用,我们还要给它添加<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />权限 这里就不多说了,上面的注解比较清楚,通过webservice我们已经把要得到的数据取回来了,接下来,我们就要把数据显示出来。这种列表形式的显示我们一般都是采用ListView控件来展示,可是我们结合第二点的需求,就是需求一个上拉和下拉的需求,这个功能ListView是没有,我们只能继承ListView自己写控件,可是自己写有点麻烦了,还好有这方面的第三插件,当然了,google也发布了一个官方的SwipeRefreshLayout插件,虽然很不错,可是它只有下拉刷新,没有上拉加载的功能。所以这里我们使用PullToRefreshListView控件,https://github.com/chrisbanes/Android-PullToRefresh,大家可以去这里下载,可惜的是,它没有给android studio提供直接加载的链接,我们直接采用加载project的方式,来加载它。好了,我们来修改一下我们之前的fragment_index.xml文件
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <!--  
  7.        ptr:ptrMode:PullToRefreshListView设置向上拉刷新还是向下拉刷新模式  
  8.                 PULL_FROM_END: 下拉刷新  
  9.               PULL_FROM_START: 上拉加载  
  10.                          both: 下拉刷新和上拉加载都有  
  11.     -->  
  12.     <com.handmark.pulltorefresh.library.PullToRefreshListView  
  13.         xmlns:ptr="http://schemas.android.com/apk/res-auto"  
  14.         android:id="@+id/pullrefresh_index_list"  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="fill_parent"  
  17.         android:cacheColorHint="#00000000"  
  18.         android:divider="@color/grey"  
  19.         android:dividerHeight="1dp"  
  20.         android:fadingEdge="none"  
  21.         android:fastScrollEnabled="false"  
  22.         android:footerDividersEnabled="false"  
  23.         android:headerDividersEnabled="false"  
  24.         android:smoothScrollbar="true"  
  25.         ptr:ptrMode="both">  
  26.     </com.handmark.pulltorefresh.library.PullToRefreshListView>  
  27.   
  28. </LinearLayout>  
PullToRefreshListView控件的使用与ListView控件的使用大体相当,没什么特别的地方,就是加载Adapter然后显示出来,但是它多了两个方法,
[java] view plain copy
  1. public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {  
  2.                         // 模拟加载任务  
  3.                           
  4.                     }  
  5.   
  6.                     @Override  
  7.                     public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {  
  8.                           
  9.                           
  10.                     }  
是用来实现上拉加载,下拉刷新的,而且都是要通过异步来进行加载的。好了,我们来修改一下首页的java代码吧
[java] view plain copy
  1. import android.app.ProgressDialog;  
  2. import android.os.Bundle;  
  3. import android.os.Handler;  
  4. import android.os.Message;  
  5. import android.support.v4.app.Fragment;  
  6. import android.util.Log;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.ListView;  
  11. import android.widget.Toast;  
  12.   
  13. import com.example.cg.zhihu_one.untils.netUntils;  
  14. import com.example.cg.zhihu_one.untils.webservicesUntils;  
  15. import com.handmark.pulltorefresh.library.PullToRefreshBase;  
  16. import com.handmark.pulltorefresh.library.PullToRefreshListView;  
  17.   
  18. /** 
  19.  * 首页 
  20.  * Created by cg on 2015/10/27. 
  21.  */  
  22. public class IndexFragment extends Fragment {  
  23.   
  24.     //定义信息等等控件  
  25.     private ProgressDialog myProgressDialog;  
  26.     private PullToRefreshListView pullrefresh_index_list;                       //定义信息列表  
  27.     @Override  
  28.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  29.                              Bundle savedInstanceState) {  
  30.         View view = inflater.inflate(R.layout.fragment_index,container,false);  
  31.         initControls(view);  
  32.         return view;  
  33.     }  
  34.     /** 
  35.      * 对下拉列表控件进行初始化,并初始化进度控件 
  36.      * @param view 
  37.      */  
  38.     private void initControls(View view) {  
  39.   
  40.         pullrefresh_index_list = (PullToRefreshListView)view.findViewById(R.id.pullrefresh_index_list);  
  41.   
  42.         //初始化数据  
  43.         initDatas();  
  44.   
  45.         // 设置下拉和上拖监听事件  
  46.         pullrefresh_index_list  
  47.                 .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {  
  48.                     @Override  
  49.                     public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {  
  50.                         // 模拟加载任务  
  51.                         //new GetDownDataTask().execute();  
  52.                     }  
  53.   
  54.                     @Override  
  55.                     public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {  
  56.                         //Log.e("onPullUpToRefresh","有反应没有啊");  
  57.                         //new GetUpDataTask().execute();  
  58.                     }  
  59.   
  60.                 });  
  61.   
  62.     }  
  63.   
  64.     /** 
  65.      * 初始时,加载10条数据上来 
  66.      */  
  67.     private void initDatas()  
  68.     {  
  69.         if(netUntils.isNetworkAvailable(getActivity())) {  
  70.             // 初始化数据和数据源  
  71.             myProgressDialog = new ProgressDialog(getActivity());  
  72.             myProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  //设置风格为圆形进度条  
  73.             myProgressDialog.setTitle("提示");                                 //设置标题  
  74.             myProgressDialog.setMessage("数据加载中,请稍等...");                 //设置内容  
  75.             myProgressDialog.setIndeterminate(false);                         //设置进度是否为不明确  
  76.             myProgressDialog.setCancelable(true);                             //设置进度条是否可以按退回键取消  
  77.             myProgressDialog.show();  
  78.   
  79.             new Thread(new Runnable() {  
  80.                 @Override  
  81.                 public void run() {  
  82.                     Message msg = new Message();  
  83.   
  84.                     try {  
  85.                         String soapObject = webservicesUntils.getIndexItemList(""""110);  
  86.   
  87.                         Log.e("soapObject",soapObject);  
  88.   
  89.   
  90.                         msg.arg1 = 1;  
  91.   
  92.                         handler.sendMessage(msg);  
  93.   
  94.                     } catch (Exception ex) {  
  95.                         msg.arg1 = 2;  
  96.                     }  
  97.                 }  
  98.             }).start();  
  99.         }else  
  100.         {  
  101.             Toast.makeText(getActivity(), "请检查您的网络是否打开!", Toast.LENGTH_LONG).show();  
  102.         }  
  103.   
  104.     }  
  105.   
  106.     Handler handler = new Handler(){  
  107.   
  108.         @Override  
  109.         public void handleMessage(Message msg) {  
  110.             if(msg.arg1==1)  
  111.             {  
  112.                 //Log.e("")  
  113.   
  114.             }else  
  115.             {  
  116.                 Toast.makeText(getActivity(), "数据读取失败!", Toast.LENGTH_LONG).show();  
  117.             }  
  118.   
  119.             myProgressDialog.dismiss();  
  120.         }  
  121.     };  
  122. }  

简单对程序说一下,这里我们只是简单的实现了一下把webservices中的数据取到,然后用log的方式显示出来,并没有对PullToRefreshListView进行设置什么,因为从网络中读取数据,这是需要时间的,所以我们采用了handle的方式。为了给用户一个更好的用户体验,我们加入了ProgressDialog控件,来显示等待的时间。
我们运行一下,你会发现,我们可以在logcat中显示出相应的信息了。
好,这说明我们的数据读取成功了,下面我们来设置一下列表中各item的布局和为PullToRefreshListView编写一个adapter.
在编写布局之前,我要说明一点,以前我们在做web程序的时候,图片我们都是在数据库中存取的图片地址,而不是采用二进制的形式把图片存在数据库中,这里我们也是采用这种方式,我们去看刚才我给的数据格式,我们的图片,也是一个网络地址,这样的话,就需要我们把这个网络图片显示出来,显示网络图片,用我们常用的ImageView是不行了,处非我们把图片下载到本地,然后再进行加载。现在有一个非常好用的volley,为我们提供了网络加载图片的功能。下面这个blog. http://blog.csdn.net/guolin_blog/article/details/17482095,一共是四篇,非常详细的介绍了它的使用,下载地址:http://download.csdn.net/detail/sinyu890807/7152015
这里我们用到的是就是其中的NetworkImageView。先把volley.jar导入我们的程序。好了,我们来看一下,item的布局文件
fragment_index_list_item.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical">  
  6.   
  7.     <RelativeLayout  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_marginTop="5dp"  
  11.         android:layout_marginBottom="5dp"  
  12.         android:layout_marginLeft="5dp"  
  13.         android:layout_marginRight="5dp">  
  14.   
  15.         <TextView  
  16.             android:id="@+id/txt_index_item_Cate"  
  17.             android:layout_width="wrap_content"  
  18.             android:layout_height="wrap_content"  
  19.             android:text="热门话题"  
  20.             android:textSize="@dimen/list_remark_size"  
  21.             android:textColor="@color/gray"/>  
  22.         <com.android.volley.toolbox.NetworkImageView  
  23.             android:id="@+id/netimg_index_item_userpic"  
  24.             android:layout_width="30dp"  
  25.             android:layout_height="30dp"  
  26.             android:src="@drawable/img_empty_followers"  
  27.             android:layout_alignParentRight="true"  
  28.             />  
  29.     </RelativeLayout>  
  30.     <LinearLayout  
  31.         android:id="@+id/linear_index_item_title"  
  32.         android:layout_width="fill_parent"  
  33.         android:layout_height="wrap_content"  
  34.         android:layout_marginTop="5dp"  
  35.         android:layout_marginBottom="5dp"  
  36.         android:layout_marginLeft="5dp"  
  37.         android:layout_marginRight="5dp"  
  38.         android:cacheColorHint="#00000000">  
  39.         <TextView  
  40.             android:id="@+id/txt_index_item_title"  
  41.             android:layout_width="fill_parent"  
  42.             android:layout_height="wrap_content"  
  43.             android:text=" "  
  44.             android:textColor="@color/black"  
  45.             android:textSize="@dimen/ActionBar_title_size"  
  46.             />  
  47.     </LinearLayout>  
  48.     <LinearLayout  
  49.         android:id="@+id/linear_index_item_content"  
  50.         android:layout_width="fill_parent"  
  51.         android:layout_height="wrap_content"  
  52.         android:layout_marginTop="5dp"  
  53.         android:layout_marginBottom="5dp"  
  54.         android:layout_marginLeft="5dp"  
  55.         android:layout_marginRight="5dp"  
  56.         android:cacheColorHint="#00000000"  
  57.         android:background="@drawable/index_list_item_background">  
  58.         <TextView  
  59.             android:id="@+id/txt_index_item_size"  
  60.             android:layout_width="0dp"  
  61.             android:layout_height="wrap_content"  
  62.             android:layout_weight="1"  
  63.             android:duplicateParentState="true"  
  64.             android:background="@drawable/index_list_item_sizebacground"  
  65.             android:text="1324K"  
  66.             android:textSize="@dimen/list_remark_size"  
  67.             android:textColor="@drawable/index_list_item_sizetextcolor"  
  68.             android:layout_marginRight="5dp"  
  69.             android:gravity="center"  
  70.             android:layout_marginTop="2dp"  
  71.             />  
  72.         <TextView  
  73.             android:id="@+id/txt_index_item_content"  
  74.             android:layout_width="0dp"  
  75.             android:layout_height="wrap_content"  
  76.             android:text=" "  
  77.             android:textSize="@dimen/list_remark_size"  
  78.             android:textColor="@drawable/index_list_item_contexttextcolor"  
  79.             android:duplicateParentState="true"  
  80.             android:lines="3"  
  81.             android:ellipsize = "end"  
  82.             android:layout_weight="8"  
  83.             />  
  84.     </LinearLayout>  
  85.   
  86. </LinearLayout>  

在这里,我为内容布局设置了动态背景还把文字颜色也设置成了动态的,这个是为了在用户点击的时候,达到相应的变化。虽然这个对于功能来说并没有什么卵用。
在drawable/index_list_item_background.xml 代码:
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   
  4.     <item  
  5.         android:state_activated="true"  
  6.         android:drawable="@color/titleBlue"  
  7.         />  
  8.     <item  
  9.         android:state_focused="false"  
  10.         android:state_pressed="true"  
  11.         android:drawable="@color/titleBlue" />  
  12.     <item android:drawable="@android:color/transparent" />  
  13. </selector>  

index_list_item.sizebacground.xml
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<!-- 没有焦点时的背景图片 -->
<item android:state_window_focused="false" android:drawable="@color/titleBlue" />

<item android:state_focused="false" android:state_pressed="true" android:drawable="@color/white" />
<!-- 默认时的背景图片-->
<item android:drawable="@color/white" />
</selector>
    这里要注意一点的是,我们一般喜欢设置一下默认的背景图片或是颜色,这里一定要把这个默认的值放在最下面,不然上面的所有变化就都不好用。
index_list_item.contexttextcolor.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   
  4.     <!-- 没有焦点时的背景图片 -->  
  5.     <item android:state_window_focused="false" android:color="@color/gray" />  
  6.   
  7.     <item android:state_focused="false" android:state_pressed="true"   android:color="@color/white" />  
  8.     <!-- 默认时的背景图片-->  
  9.     <item android:color="@color/gray" />  
  10.   
  11. </selector>  

index_list_item_sizetextcolor.xml
[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   
  4.     <!-- 没有焦点时的背景图片 -->  
  5.     <item android:state_window_focused="false" android:color="@color/white" />  
  6.   
  7.     <item android:state_focused="false" android:state_pressed="true"   android:color="@color/titleBlue" />  
  8.     <!-- 默认时的背景图片-->  
  9.     <item android:color="@color/white" />  
  10.   
  11. </selector>  

    好,item布局文件搞定,我们来看一下Adapter的代码:
Index_lv_Adapter.java
[java] view plain copy
  1. import android.content.Context;  
  2. import android.graphics.Bitmap;  
  3. import android.view.LayoutInflater;  
  4. import android.view.View;  
  5. import android.view.ViewGroup;  
  6. import android.widget.BaseAdapter;  
  7. import android.widget.LinearLayout;  
  8. import android.widget.TextView;  
  9.   
  10. import com.android.volley.RequestQueue;  
  11. import com.android.volley.toolbox.ImageLoader;  
  12. import com.android.volley.toolbox.NetworkImageView;  
  13. import com.android.volley.toolbox.Volley;  
  14. import com.example.cg.zhihu_one.R;  
  15. import com.example.cg.zhihu_one.models.IndexList;  
  16. import com.example.cg.zhihu_one.untils.imagesUntils;  
  17.   
  18. import java.util.List;  
  19.   
  20. /** 
  21.  * 首页信息列表Adapter 
  22.  * Created by cg on 2015/10/30. 
  23.  */  
  24. public class Index_lv_Adapter extends BaseAdapter {  
  25.   
  26.     private List<IndexList> list_index;                                  //定义显示的信息列表  
  27.     private LayoutInflater inflater;  
  28.   
  29.     //定义volley  
  30.     private RequestQueue mQueue;  
  31.     private ImageLoader imageLoader;  
  32.     private Context context;  
  33.   
  34.     public Index_lv_Adapter(Context context,List<IndexList> list_index) {  
  35.         this.context = context;  
  36.         this.inflater = LayoutInflater.from(context);  
  37.         this.list_index = list_index;  
  38.   
  39.         mQueue = Volley.newRequestQueue(context);  
  40.         imageLoader = new ImageLoader(mQueue,new imagesUntils.BitmapCache(){  
  41.             @Override  
  42.             public Bitmap getBitmap(String s) {  
  43.                 return null;  
  44.             }  
  45.   
  46.             @Override  
  47.             public void putBitmap(String s, Bitmap bitmap) {  
  48.   
  49.             }  
  50.         });  
  51.     }  
  52.   
  53.     @Override  
  54.     public int getCount() {  
  55.         return list_index.size();  
  56.     }  
  57.   
  58.     @Override  
  59.     public Object getItem(int position) {  
  60.         return list_index.get(position);  
  61.     }  
  62.   
  63.     @Override  
  64.     public long getItemId(int position) {  
  65.         return position;  
  66.     }  
  67.   
  68.     @Override  
  69.     public View getView(final int position, View convertView, ViewGroup parent) {  
  70.         final index_list_info listclass;  
  71.         if(convertView==null)  
  72.         {  
  73.             listclass = new index_list_info();  
  74.             convertView = inflater.inflate(R.layout.fragment_index_list_item,null,false);  
  75.             listclass.userpic = (NetworkImageView)convertView.findViewById(R.id.netimg_index_item_userpic);  
  76.             listclass.item_title = (TextView)convertView.findViewById(R.id.txt_index_item_title);  
  77.             listclass.item_size = (TextView)convertView.findViewById(R.id.txt_index_item_size);  
  78.             listclass.item_content = (TextView)convertView.findViewById(R.id.txt_index_item_content);  
  79.             listclass.linear_index_item_title = (LinearLayout)convertView.findViewById(R.id.linear_index_item_title);  
  80.             listclass.linear_index_item_content = (LinearLayout)convertView.findViewById(R.id.linear_index_item_content);  
  81.   
  82.             convertView.setTag(listclass);  
  83.         }  
  84.         else  
  85.         {  
  86.             listclass = (index_list_info)convertView.getTag();  
  87.         }  
  88.   
  89.         //为图片控件加载图片,采用NetworkImageView控件。  
  90.         //第一项是加载图片控件的默认图片,一般是图片加载中,这样的图片  
  91.         //第二项是当发生错误的时候加载的图片,如网络图片路径不对或是加载失败的时候显示的图片  
  92.         //第三项就是加载网络图片了  
  93.         listclass.userpic.setDefaultImageResId(R.drawable.img_empty_followers);  
  94.         listclass.userpic.setErrorImageResId(R.drawable.img_empty_followers);  
  95.         listclass.userpic.setImageUrl(list_index.get(position).getUserPic(), imageLoader);  
  96.   
  97.         listclass.item_title.setText(list_index.get(position).getQuestionTitle());  
  98.         listclass.item_size.setText(list_index.get(position).getQuestionSize());  
  99.         listclass.item_content.setText(list_index.get(position).getQuestionContent());  
  100.   
  101.   
  102.         // 只所以在这里添加点击事件,而不是为控件添加onitemclistener事件,  
  103.         // 是因为,在一个item里,点击上半部分和下半部分将要跳转的页面不同  
  104.         listclass.linear_index_item_content.setOnClickListener(new View.OnClickListener() {  
  105.             @Override  
  106.             public void onClick(View v) {  
  107.                 /*Intent cIntent = new Intent(); 
  108.                 cIntent.setClass(context, Index_detailActivity.class); 
  109.                 cIntent.putExtra("questionID", list_index.get(position).getQuestionID()); 
  110.                 cIntent.putExtra("questionTitle",list_index.get(position).getQuestionTitle()); 
  111.                 context.startActivity(cIntent);*/  
  112.             }  
  113.         });  
  114.   
  115.         return convertView;  
  116.     }  
  117.   
  118.   
  119.     public class index_list_info  
  120.     {  
  121.         NetworkImageView userpic;  
  122.         TextView item_title;  
  123.         TextView item_size;  
  124.         TextView item_content;  
  125.         LinearLayout linear_index_item_title;  
  126.         LinearLayout linear_index_item_content;  
  127.     }  
  128. }  

这里我把volley处理图片,防止OOM的代码单独拿出来,放到一个公共类里面,供以后的程序的调用。
[java] view plain copy
  1. imagesUntils.java  
  2. import android.graphics.Bitmap;  
  3. import android.graphics.BitmapFactory;  
  4. import android.util.LruCache;  
  5.   
  6. import com.android.volley.toolbox.ImageLoader;  
  7. /** 
  8.  * 各种对图片进行操作的通用方法 
  9.  * Created by cg on 2015/10/30. 
  10.  */  
  11. public class imagesUntils {  
  12.     /** 
  13.      * 显示保存在手机中的图片,加入了缩小图片的功能,防止OOM 
  14.      * 
  15.      * @param imgPath            文件路径 
  16.      * @param screenWidth        手机宽 
  17.      * @param screenHeight       手机高 
  18.      * @return                   Bitmap类型 
  19.      */  
  20.     public static Bitmap viewPic(String imgPath,int screenWidth,int screenHeight)  
  21.     {  
  22.   
  23.         BitmapFactory.Options options = new BitmapFactory.Options();  
  24.         options.inJustDecodeBounds = true;                                //不去真的解析图片 获取图片头部信息  
  25.         Bitmap mitmap = BitmapFactory.decodeFile(imgPath, options);       //取得图片的信息  
  26.         int height = options.outHeight;                                   //图片的高  
  27.         int width = options.outWidth;                                     //图片的宽  
  28.   
  29.         // 得到手机屏幕宽高比  
  30.         int scaleX=width/screenHeight;  
  31.         int scaleY=height/screenWidth;  
  32.         int scale=1;                                                      //默认缩小比例是1  
  33.         // 如果高的比例大,并且比例大于1,也就是图片的高要大于手机的高  
  34.         if(scaleX>scaleY && scaleY>=1)  
  35.         {  
  36.             scale=scaleX;  
  37.         }  
  38.   
  39.         if(scaleY>scaleX && scaleX>=1)  
  40.         {  
  41.             scale=scaleY;  
  42.         }  
  43.   
  44.         options.inJustDecodeBounds=false;                                  //真的去解析图片  
  45.         options.inSampleSize=scale;                                        //按比例缩小图片  
  46.         Bitmap bm = BitmapFactory.decodeFile(imgPath, options);  
  47.         return bm;  
  48.     }  
  49.   
  50.   
  51.     /** 
  52.      * 对图片进行防OOM处理 
  53.      */  
  54.     public static class BitmapCache implements ImageLoader.ImageCache{  
  55.   
  56.         private LruCache<String,Bitmap> mCache;  
  57.   
  58.         public BitmapCache(){  
  59.             int maxSize = 10*1024*1024;  
  60.             mCache = new LruCache<String, Bitmap>(maxSize){  
  61.                 protected int sizeOf(String key,Bitmap bitmap)  
  62.                 {  
  63.                     return bitmap.getRowBytes() * bitmap.getHeight();  
  64.                 }  
  65.             };  
  66.         }  
  67.   
  68.         @Override  
  69.         public Bitmap getBitmap(String url) {  
  70.             return mCache.get(url);  
  71.         }  
  72.   
  73.         @Override  
  74.         public void putBitmap(String url, Bitmap bitmap) {  
  75.             mCache.put(url,bitmap);  
  76.         }  
  77.     }  
  78. }  

Adapter程序完成,我们来修改首页的程序,为PullToRefreshListView控件绑定数据。修改后的代码如下:

[java] view plain copy
  1. import android.app.ProgressDialog;  
  2. import android.os.AsyncTask;  
  3. import android.os.Bundle;  
  4. import android.os.Handler;  
  5. import android.os.Message;  
  6. import android.support.v4.app.Fragment;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.ViewGroup;  
  10. import android.widget.ListView;  
  11. import android.widget.Toast;  
  12.   
  13. import com.example.cg.zhihu_one.Adapters.Index_lv_Adapter;  
  14. import com.example.cg.zhihu_one.models.IndexList;  
  15. import com.example.cg.zhihu_one.untils.netUntils;  
  16. import com.example.cg.zhihu_one.untils.webservicesUntils;  
  17. import com.handmark.pulltorefresh.library.PullToRefreshBase;  
  18. import com.handmark.pulltorefresh.library.PullToRefreshListView;  
  19.   
  20. import org.json.JSONArray;  
  21. import org.json.JSONException;  
  22. import org.json.JSONObject;  
  23. import org.xmlpull.v1.XmlPullParserException;  
  24.   
  25. import java.io.IOException;  
  26. import java.util.ArrayList;  
  27. import java.util.List;  
  28.   
  29. /** 
  30.  * 首页 
  31.  * Created by cg on 2015/10/27. 
  32.  */  
  33. public class IndexFragment extends Fragment {  
  34.   
  35.     //定义信息等等控件  
  36.     private ProgressDialog myProgressDialog;  
  37.     private PullToRefreshListView pullrefresh_index_list;                       //定义信息列表  
  38.   
  39.     private List<IndexList> list_index;                                         //定义显示数据的list  
  40.     private Index_lv_Adapter indexAdapter;                                      //定义Adapter  
  41.   
  42.     @Override  
  43.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  44.                              Bundle savedInstanceState) {  
  45.         View view = inflater.inflate(R.layout.fragment_index,container,false);  
  46.         initControls(view);  
  47.         return view;  
  48.     }  
  49.     /** 
  50.      * 对下拉列表控件进行初始化,并初始化进度控件 
  51.      * @param view 
  52.      */  
  53.     private void initControls(View view) {  
  54.   
  55.         pullrefresh_index_list = (PullToRefreshListView)view.findViewById(R.id.pullrefresh_index_list);  
  56.   
  57.         list_index = new ArrayList<>();  
  58.   
  59.         //初始化数据  
  60.         initDatas();  
  61.   
  62.         // 设置下拉和上拖监听事件  
  63.         pullrefresh_index_list  
  64.                 .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {  
  65.                     @Override  
  66.                     public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {  
  67.                         // 模拟加载任务  
  68.                         new GetDownDataTask().execute();  
  69.                     }  
  70.   
  71.                     @Override  
  72.                     public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {  
  73.                         //Log.e("onPullUpToRefresh","有反应没有啊");  
  74.                         new GetUpDataTask().execute();  
  75.                     }  
  76.   
  77.                 });  
  78.   
  79.     }  
  80.   
  81.     /** 
  82.      * 初始时,加载10条数据上来 
  83.      */  
  84.     private void initDatas()  
  85.     {  
  86.         if(netUntils.isNetworkAvailable(getActivity())) {  
  87.             // 初始化数据和数据源  
  88.             myProgressDialog = new ProgressDialog(getActivity());  
  89.             myProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  //设置风格为圆形进度条  
  90.             myProgressDialog.setTitle("提示");                                 //设置标题  
  91.             myProgressDialog.setMessage("数据加载中,请稍等...");                 //设置内容  
  92.             myProgressDialog.setIndeterminate(false);                         //设置进度是否为不明确  
  93.             myProgressDialog.setCancelable(true);                             //设置进度条是否可以按退回键取消  
  94.             myProgressDialog.show();  
  95.   
  96.             new Thread(new Runnable() {  
  97.                 @Override  
  98.                 public void run() {  
  99.                     Message msg = new Message();  
  100.   
  101.                     try {  
  102.   
  103.                         //得到数据  
  104.                         String soapObject = webservicesUntils.getIndexItemList(""""110);  
  105.   
  106.                         //判断如果数据返回的不是错误代码0,则对返回的json数据进行解析,将数据存入List中  
  107.                         if (soapObject != "0") {  
  108.                             try {  
  109.   
  110.                                 JSONArray jsonArray = new JSONArray(soapObject);  
  111.   
  112.                                 for (int i = 0; i < jsonArray.length(); i++) {  
  113.                                     JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);  
  114.   
  115.                                     IndexList comm = new IndexList();  
  116.                                     comm.setUserPic(jsonObject2.getString("userPic"));  
  117.                                     comm.setQuestionTitle(jsonObject2.getString("questionTitle"));  
  118.                                     comm.setQuestionSize(jsonObject2.getString("questionSize"));  
  119.                                     comm.setQuestionContent(jsonObject2.getString("questionContent"));  
  120.                                     comm.setQuestionID(jsonObject2.getInt("questionID"));  
  121.   
  122.                                     list_index.add(comm);  
  123.                                 }  
  124.                             } catch (JSONException e) {  
  125.                                 // TODO Auto-generated catch block  
  126.                                 e.printStackTrace();  
  127.                             }  
  128.                         }  
  129.   
  130.   
  131.   
  132.                         msg.arg1 = 1;  
  133.   
  134.                         handler.sendMessage(msg);  
  135.   
  136.                     } catch (Exception ex) {  
  137.                         msg.arg1 = 2;  
  138.                     }  
  139.                 }  
  140.             }).start();  
  141.         }else  
  142.         {  
  143.             Toast.makeText(getActivity(), "请检查您的网络是否打开!", Toast.LENGTH_LONG).show();  
  144.         }  
  145.   
  146.     }  
  147.   
  148.     Handler handler = new Handler(){  
  149.   
  150.         @Override  
  151.         public void handleMessage(Message msg) {  
  152.             if(msg.arg1==1)  
  153.             {  
  154.                 if(list_index!=null)  
  155.                 {  
  156.                     //设置适配器  
  157.                     indexAdapter = new Index_lv_Adapter(getActivity(),list_index);  
  158.                     pullrefresh_index_list.setAdapter(indexAdapter);  
  159.                 }else  
  160.                 {  
  161.                     Toast.makeText(getActivity(), "无数据加载!", Toast.LENGTH_LONG).show();  
  162.                 }  
  163.   
  164.             }else  
  165.             {  
  166.                 Toast.makeText(getActivity(), "数据读取失败!", Toast.LENGTH_LONG).show();  
  167.             }  
  168.   
  169.             myProgressDialog.dismiss();  
  170.         }  
  171.     };  
  172.   
  173.     /** 
  174.      * 下拉时,更新数据,从list中提取第一条数据也就是最新的一条,传回,以供判断是否有新的数据,如果有,则对listView进行刷新 
  175.      * 通过return将得到的数据返回给protected void onPostExecute(String result),以便在前台显示 
  176.      */  
  177.     private class GetDownDataTask extends AsyncTask<Void, Void, String>  
  178.     {  
  179.   
  180.         //异步取数据  
  181.         @Override  
  182.         protected String doInBackground(Void... params)  
  183.         {  
  184.             try  
  185.             {  
  186.                 //这里调用一个webServices取新添加的数据  
  187.                 //原理:取现在list中最新的数据,去后台数据中进行对比,如果有比这个新的数据,就取,没有则返回0  
  188.                 String soapObject = webservicesUntils.getIndexItemList_refresh(String.valueOf(list_index.get(0).getQuestionID()));  
  189.   
  190.                 return soapObject;  
  191.             }  catch (XmlPullParserException e) {  
  192.                 e.printStackTrace();  
  193.             } catch (IOException e) {  
  194.                 e.printStackTrace();  
  195.             }  
  196.             return "" ;  
  197.         }  
  198.   
  199.         //将数据显示在前台  
  200.         @Override  
  201.         protected void onPostExecute(String result)  
  202.         {  
  203.             if(!result.equals("0"))  
  204.             {  
  205.                 try {  
  206.   
  207.                     //我们采用了.add(location,comm)方法,指定了插入的位置,这样就把新的数据直接插入到前面  
  208.                     //list_index.clear();                //清空List<>中的数据  
  209.   
  210.                     JSONArray jsonArray = new JSONArray(result);  
  211.   
  212.                     for (int i = 0; i < jsonArray.length(); i++) {  
  213.                         JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);  
  214.   
  215.                         IndexList comm = new IndexList();  
  216.                         comm.setUserPic(jsonObject2.getString("userPic"));  
  217.                         comm.setQuestionTitle(jsonObject2.getString("questionTitle"));  
  218.                         comm.setQuestionSize(jsonObject2.getString("questionSize"));  
  219.                         comm.setQuestionContent(jsonObject2.getString("questionContent"));  
  220.                         comm.setQuestionID(jsonObject2.getInt("questionID"));  
  221.   
  222.                         list_index.add(0,comm);  
  223.   
  224.                     }  
  225.                     indexAdapter.notifyDataSetChanged();  
  226.                     //num=1;  
  227.                 } catch (JSONException e) {  
  228.                     // TODO Auto-generated catch block  
  229.                     e.printStackTrace();  
  230.                 }  
  231.             }  
  232.             //刷新结束,必须加上此句,不然下面的加载图标一下在  
  233.             pullrefresh_index_list.onRefreshComplete();  
  234.         }  
  235.     }  
  236.   
  237.     /** 
  238.      * 向上刷新加载更多的数据 
  239.      */  
  240.     public class GetUpDataTask extends AsyncTask<Void, Void, String> {  
  241.   
  242.         @Override  
  243.         protected String doInBackground(Void... params) {  
  244.   
  245.             try {  
  246.   
  247.                 String soapObject = webservicesUntils.getIndexItemList("""", list_index.size() + 110);  
  248.   
  249.                 return soapObject;  
  250.   
  251.             } catch (Exception ex) {  
  252.                 return "0";  
  253.             }  
  254.   
  255.         }  
  256.   
  257.         @Override  
  258.         protected void onPostExecute(String result) {  
  259.             if (result != "0") {  
  260.                 try {  
  261.   
  262.                     JSONArray jsonArray = new JSONArray(result);  
  263.   
  264.                     for (int i = 0; i < jsonArray.length(); i++) {  
  265.                         JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);  
  266.   
  267.                         IndexList comm = new IndexList();  
  268.                         comm.setUserPic(jsonObject2.getString("userPic"));  
  269.                         comm.setQuestionTitle(jsonObject2.getString("questionTitle"));  
  270.                         comm.setQuestionSize(jsonObject2.getString("questionSize"));  
  271.                         comm.setQuestionContent(jsonObject2.getString("questionContent"));  
  272.                         comm.setQuestionID(jsonObject2.getInt("questionID"));  
  273.   
  274.                         list_index.add(comm);  
  275.                     }  
  276.   
  277.                     indexAdapter.notifyDataSetChanged();  
  278.                 } catch (JSONException e) {  
  279.                     // TODO Auto-generated catch block  
  280.                     e.printStackTrace();  
  281.                 }  
  282.             }  
  283.             //刷新结束,必须加上此句,不然下面的加载图标一下在  
  284.             pullrefresh_index_list.onRefreshComplete();  
  285.         }  
  286.   
  287.     }  
  288. }  
  289.   
  290. 显示的结果图:  

在这里,要说明的一点是PullToRefreshListView控件的setOnRefreshListener方法, 它里面有两个实现方法, 一个是我们在程序中所使用的
new PullToRefreshBase.OnRefreshListener2<ListView>()方法, 这个是既有上拉,又有下拉的方法,还有一个是
new PullToRefreshBase.OnRefreshListener<ListView>()方法,这个是只有上拉
可通过http://blog.csdn.net/lmj623565791/article/details/38238749这个blog了解更细的使用说明


转自:http://blog.csdn.net/chenguang79/article/details/49508781




0 0
原创粉丝点击