PullToRefreshScrollView的上拉加载、下拉刷新

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,依赖成功

 

 

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:text="标题"
        android:gravity="center" />
    <com.handmark.pulltorefresh.library.PullToRefreshScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/sc_scrollview">
        <LinearLayout android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/layout"
            android:orientation="vertical">
             <TextView android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:text="11111111111111"/>
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:text="11111111111111"/>
           
            <com.bwie.test.MyGridView  
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:numColumns="2"
                android:id="@+id/gvv_gridview"></com.bwie.test.MyGridView>
             <TextView android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:text="11111111111111"/>
            <TextView android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:text="11111111111111"/>
           
           
            
        </LinearLayout>
    </com.handmark.pulltorefresh.library.PullToRefreshScrollView>

</LinearLayout>

 

 

//---------gridView 的布局文件---------fenlei_item_gridview.xml--------------------------------

//注意:TextView的高度要有具体高度不能是包裹内容,不然每次刷新,都会有一段空白距离

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
<ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher"
        android:id="@+id/iv_fenlei_grid_goods_img"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:id="@+id/tv_fenlei_grid_goods_name"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_fenlei_grid_shop_price"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:id="@+id/tv_fenlei_grid_market_price"/>
    </LinearLayout>
</LinearLayout>

//--------------------------MainActivity中----------------=========================

package com.bwie.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.GridView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
    PullToRefreshScrollView sc_scrollview;
    private LinearLayout layout;
    //数据网址
        private String urlPath="http://m.yunifang.com/yunifang/mobile/category/list?random=12024&encode=815abd1d3bb7ad28ade130e19dad79dc";
       //定义集合
        private List<FenLeiGoods> fenLeiGoodses=new ArrayList<FenLeiGoods>();
        //定义适配器
        private MyFenLeiAdapter adapter;
        private MyGridView gvv_gridview;


    //---------------------------------------------
    //使用Handler更新UI
        private Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {

                switch (msg.what){
                    case 0:   
                        //获得数据
                        String text= (String) msg.obj;
                        //解析数据json串
                        tojson(text);
                        break;
                }
            }


        };
        
    
        
    //-------------------------------------------------------      
        //解析数据json串
        private void tojson(String text) {
            try {
                JSONObject obj=new JSONObject(text);
                JSONObject data=obj.getJSONObject("data");
                JSONArray goodsBrief=data.getJSONArray("goodsBrief");
                for (int i=0;i<goodsBrief.length();i++){
                    JSONObject json=goodsBrief.getJSONObject(i);

                    String id=json.getString("id");
                    String goods_name=json.getString("goods_name");
                    String shop_price=json.getString("shop_price");
                    String market_price=json.getString("market_price");
                    String goods_img=json.getString("goods_img");
                    String reservable=json.getString("reservable");
                    String efficacy=json.getString("efficacy");
                   //添加到集合
                    FenLeiGoods fenleigoodss=new FenLeiGoods(id,goods_name,shop_price,market_price,goods_img,reservable,efficacy,null);
                    fenLeiGoodses.add(fenleigoodss);

                    Log.i("kkkkkkkkkkkkkkkkk",fenLeiGoodses.toString());
                    //设置适配器
                    if (adapter==null) {
                        adapter = new MyFenLeiAdapter(fenLeiGoodses, this);
                        gvv_gridview.setAdapter(adapter);
                    }else{
                        adapter.notifyDataSetChanged();
                    }
                   

                    
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //scrollview内的线性布局
        layout = (LinearLayout) findViewById(R.id.layout);
      //设置当前焦点,防止打开Activity出现在ListView位置问题
        layout.setFocusable(true);
        layout.setFocusableInTouchMode(true);
        layout.requestFocus();
        
        //找到控件   PullToRefreshScrollView
        sc_scrollview=(PullToRefreshScrollView) findViewById(R.id.sc_scrollview);
        //找到控件   自定义的MyGridView
        gvv_gridview = (MyGridView) findViewById(R.id.gvv_gridview);
        // 刷新label的设置
        sc_scrollview.getLoadingLayoutProxy().setLastUpdatedLabel(
                    "上次刷新时间" );
        sc_scrollview.getLoadingLayoutProxy()
                   .setPullLabel( "下拉刷新");
        //sc_scrollview.getLoadingLayoutProxy().setRefreshingLabel( "refreshingLabel");
               
        sc_scrollview.getLoadingLayoutProxy().setReleaseLabel("松开即可刷新" );
                    

        huodeshuju();
        //设置刷新的模式
        sc_scrollview.setMode(Mode.BOTH);//both  可以上拉、可以下拉
        sc_scrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                //fenLeiGoodses.clear();
                huodeshuju();
                //创建一个方法结束刷新
                new FinishRefresh().execute();
                //刷新适配器
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                //fenLeiGoodses.clear();
                huodeshuju();
                //创建一个方法结束刷新
                new FinishRefresh().execute();
                //刷新适配器
                adapter.notifyDataSetChanged();
            }
        });
       
        
        
    }
    
    
  //完成刷新的方法
    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            //刷新完成
            sc_scrollview.onRefreshComplete();
        }
    }
    
//---------------------------------------
    //获得网络数据
    private void huodeshuju() {        
         new Thread(){
             @Override
             public void run() {
                 try {
                     URL url=new URL(urlPath);                    
                     HttpURLConnection urlconnection= (HttpURLConnection) url.openConnection();
                     urlconnection.setConnectTimeout(5000);
                     urlconnection.setReadTimeout(5000);
                     urlconnection.setRequestMethod("GET");
                     //urlconnection.connect();
                     int code=urlconnection.getResponseCode();
                     if (code==200){
                         InputStream inputstream=urlconnection.getInputStream();
                         BufferedReader reader=new BufferedReader(new InputStreamReader(inputstream));
                         String line;
                         StringBuffer buffer=new StringBuffer();
                         while ((line=reader.readLine())!=null){
                             buffer.append(line);
                         }
                         String str=buffer.toString();
                         Log.i("数据:", str);
                         
                         Message message=new Message();
                         message.what=0;
                         message.obj=str;
                         handler.sendMessage(message);
                     }

                 } catch (IOException e) {
                     e.printStackTrace();
                 }

             }
         }.start();

     }


    
    
}

//------------------bean包封装了商品的属性---------------------------------------------------

package com.bwie.test;

public class FenLeiGoods {
    private String id;
    private String goods_name;
    private String shop_price;
    private String market_price;
    private String goods_img;
    private String reservable;
    private String efficacy;
    private String watermarkUrl;

    public FenLeiGoods(String id, String goods_name, String shop_price, String market_price, String goods_img, String reservable, String efficacy, String watermarkUrl) {
        this.id = id;
        this.goods_name = goods_name;
        this.shop_price = shop_price;
        this.market_price = market_price;
        this.goods_img = goods_img;
        this.reservable = reservable;
        this.efficacy = efficacy;
        this.watermarkUrl = watermarkUrl;
    }

    public FenLeiGoods() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getGoods_name() {
        return goods_name;
    }

    public void setGoods_name(String goods_name) {
        this.goods_name = goods_name;
    }

    public String getShop_price() {
        return shop_price;
    }

    public void setShop_price(String shop_price) {
        this.shop_price = shop_price;
    }

    public String getMarket_price() {
        return market_price;
    }

    public void setMarket_price(String market_price) {
        this.market_price = market_price;
    }

    public String getGoods_img() {
        return goods_img;
    }

    public void setGoods_img(String goods_img) {
        this.goods_img = goods_img;
    }

    public String getReservable() {
        return reservable;
    }

    public void setReservable(String reservable) {
        this.reservable = reservable;
    }

    public String getEfficacy() {
        return efficacy;
    }

    public void setEfficacy(String efficacy) {
        this.efficacy = efficacy;
    }

    public String getWatermarkUrl() {
        return watermarkUrl;
    }

    public void setWatermarkUrl(String watermarkUrl) {
        this.watermarkUrl = watermarkUrl;
    }

    @Override
    public String toString() {
        return "FenLeiGoods{" +
                "id='" + id + '\'' +
                ", goods_name='" + goods_name + '\'' +
                ", shop_price='" + shop_price + '\'' +
                ", market_price='" + market_price + '\'' +
                ", goods_img='" + goods_img + '\'' +
                ", reservable='" + reservable + '\'' +
                ", efficacy='" + efficacy + '\'' +
                ", watermarkUrl='" + watermarkUrl + '\'' +
                '}';
    }
}

 

//-------------自定义的适配器------------------------------

package com.bwie.test;

import java.util.List;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyFenLeiAdapter extends BaseAdapter{

     private List<FenLeiGoods> fenLeiGoodses;
        private Context context;

        public MyFenLeiAdapter(List<FenLeiGoods> fenLeiGoodses, Context context) {
            this.fenLeiGoodses = fenLeiGoodses;
            this.context = context;
        }

        @Override
        public int getCount() {
            return fenLeiGoodses.size();
        }

        @Override
        public Object getItem(int position) {
            return fenLeiGoodses.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder=null;
            FenLeiGoods fenLeiGoodss=fenLeiGoodses.get(position);
            if (convertView==null){
                convertView=View.inflate(context, R.layout.fenlei_item_gridview,null);
                holder=new ViewHolder();
                holder.goods_img= (ImageView) convertView.findViewById(R.id.iv_fenlei_grid_goods_img);
                holder.goods_name= (TextView) convertView.findViewById(R.id.tv_fenlei_grid_goods_name);
                holder.shop_price= (TextView) convertView.findViewById(R.id.tv_fenlei_grid_shop_price);
                holder.market_price= (TextView) convertView.findViewById(R.id.tv_fenlei_grid_market_price);
                convertView.setTag(holder);

            }
            holder= (ViewHolder) convertView.getTag();
            holder.goods_name.setText(fenLeiGoodss.getGoods_name());
            holder.shop_price.setText(fenLeiGoodss.getShop_price());
            holder.market_price.setText(fenLeiGoodss.getMarket_price());
            ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context));
            DisplayImageOptions options=new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).build();
            ImageLoader.getInstance().displayImage(fenLeiGoodss.getGoods_img(),holder.goods_img,options);

            return convertView;
        }
        static class ViewHolder{
            public TextView goods_name;
            public TextView shop_price;
            public TextView market_price;
            public ImageView goods_img;



        }
}

 

//---------自定义Gridview可以显示gridview全部的条目------------------------

package com.bwie.test;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

public class MyGridView extends GridView{

    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public MyGridView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
                super.onMeasure(widthMeasureSpec, expandSpec);
    }
    

}

posted on 2016-10-07 10:49  巫山老妖  阅读(6127)  评论(0编辑  收藏  举报