PullToRefreshListView上拉加载、下拉刷新 eclipse项目

 

说明:此项目实在fragment中的,需要依赖library完成,还用到了Xuitls.jar包、使用了Pull解析XML

eclipse中的项目:

 

//注意:此刷新功能是使用的第三方的PullToRefreshScrollView,因此需要导入第三方library作为依赖

 

步骤:导入第三方library,依赖:点击你的应用程序右击,再点击properties,再点击Android,再点击add,选中library,点击OK

 

//请求网路需要配置完网络权限   <uses-permission android:name="android.permission.INTERNET"/>

 

 

 

Android Studio中的项目:导入library,并依赖

 

导入:点击File,New——>import Module 打开libray的位置,选中libray ,点击OK

依赖:点击Android studio工具栏中的有多个小方块的那个,再点击 app,再点击Dependencies,再点击+符号,再点击Module dependency,选中libray,点击OK,依赖成功

 

//------------------------------主布局文件-----------------------------------------

注意:高度为match_parent或fill_parent不能为wrap_content,为wrap_content时不显示数据,这个为什么我也不知道,请求大神指教。

<com.handmark.pulltorefresh.library.PullToRefreshListView
        android:layout_width="fill_parent"        
        android:layout_height="match_parent"
        android:id="@+id/lv_list"></com.handmark.pulltorefresh.library.PullToRefreshListView>

 

//------------------------------------------------------------

package com.bwie.test.fragment;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.XListView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.bwie.test.R;
import com.bwie.test.adapter.MyAdapter;
import com.bwie.test.bean.News;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

public class Fragment2 extends Fragment{
    
    private List<News> news=new ArrayList<News>();
    private MyAdapter adapter;
    //设置页数、分页加载
    private int ye=1;
    private PullToRefreshListView lv;

    //使用Handler更新UI
    private Handler handler=new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0:    
                //获得请求的网络数据
                String text=(String) msg.obj;
                //解析XML
                toXml(text);
                break;

            default:
                break;
            }
        }        
    };
    
    //解析XML
    private void toXml(String text) {
        News newss=null;
        try {                                
            //将读取到的结果码   添加到XML里面
            XmlPullParser Parser = Xml.newPullParser();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(text.getBytes());
            Parser.setInput(byteArrayInputStream, "utf-8");
            //通过parse获得项目类型      相当于文件里面的属性吧
            int eventType = Parser.getEventType();
            //判断
            while ((eventType != XmlPullParser.END_DOCUMENT)) {
                String name = Parser.getName();
                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (name.equals("news")) {
                        newss = new News();
                    } else if (name.equals("id")) {
                        String id = Parser.nextText();
                        newss.setId(id);
                    } else if (name.equals("title")) {
                        String title = Parser.nextText();
                        newss.setTitle(title);
                    } else if (name.equals("body")) {
                        String body = Parser.nextText();
                        newss.setBody(body);
                    } else if (name.equals("commentCount")) {
                        String commentCount = Parser.nextText();
                        newss.setCommentCount(commentCount);
                    }
                    else if (name.equals("author")) {
                        String author = Parser.nextText();
                        newss.setAuthor(author);
                    }
                    else if (name.equals("pubDate")) {
                        String pubDate = Parser.nextText();
                        newss.setPubDate(pubDate);
                    }
                    break;
                    case XmlPullParser.END_TAG:
                        if (name.equals("news")) {
                           news.add(newss);
                           
                         //更新适配器
                           if (adapter == null) {
                                adapter = new MyAdapter(news,getActivity());
                                     lv.setAdapter(adapter);
                               } else {
                               adapter .notifyDataSetChanged();
                              }
                            
                        }
                        break;
                default:
                    break;
                }
                eventType=Parser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    };
    
//-------------------onCreateView------------------    
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_item2, null);
        //找到控件
        lv=(PullToRefreshListView) view.findViewById(R.id.lv);
        //获得网络数据
        huodeshuju(ye);
        //设置适配器
        adapter = new MyAdapter(news, getActivity());
        lv.setAdapter(adapter);
        //设置PullToRefreshListView的模式——BOTH时,为可以上拉加载、可以下拉刷新
        lv.setMode(Mode.BOTH);
        //两个方法一样
        //lv.setMode(PullToRefreshBase.Mode.BOTH);
        
        /*lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                // TODO Auto-generated method stub
                
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                // TODO Auto-generated method stub
                
            }
        });*/
        //设置刷新的监听
        lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override//下拉刷新
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //重新定义为第一页
                ye=1;
                Toast.makeText(getActivity(),""+ye,Toast.LENGTH_SHORT).show();
               //获得数据
             huodeshuju(ye);
                //刷新适配器
                adapter.notifyDataSetChanged();
                //创建一个方法结束刷新
                new FinishRefresh().execute();
            }

            @Override//上拉加载更多
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
             //使页数加1
                ye++;
                Toast.makeText(getActivity(),""+ye,Toast.LENGTH_SHORT).show();
                huodeshuju(ye);
                adapter.notifyDataSetChanged();
                new FinishRefresh().execute();
            }
        });
        
        
        return view;
    }
    
//------------获得网络数据----------------------
    //使用Xuitls.jar包
    private void huodeshuju(int ye) {
        //创建httpUtils
        HttpUtils httpUtils=new HttpUtils();
        httpUtils.send(HttpMethod.GET, "http://www.oschina.net/action/api/news_list?catalog=1&pageIndex="+ye+"&pageSize=20", new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                
                
            }

            @Override//请求成功
            public void onSuccess(ResponseInfo<String> arg0) {
                String str=arg0.result;
                Log.i("数据", str);
                Message message=new Message();
                message.what=0;
                message.obj=str;
                handler.sendMessage(message);
                
            }
        });
        
    }
//-------------------
    
    //完成刷新的方法
    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {

     try {
            //停留2秒
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            //刷新完成
            lv.onRefreshComplete();
        }
    }
    

}

posted on 2016-09-25 21:01  巫山老妖  阅读(563)  评论(0编辑  收藏  举报