PullToRefreshGridView上拉加载、下拉刷新

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

 

//-------------------一下是主布局文件-------------------------------

//注意:当自己定义属性是高度要填充父窗体,如果是包裹内容,会不显示数据

<RelativeLayout 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"
    >
    <com.handmark.pulltorefresh.library.PullToRefreshGridView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/gv_gridview"
         android:numColumns="2"></com.handmark.pulltorefresh.library.PullToRefreshGridView>
    

   <!-- <com.handmark.pulltorefresh.library.PullToRefreshGridView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/gv_gridview"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:numColumns="2"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        android:columnWidth="100dp"
        android:stretchMode="columnWidth"
        android:gravity="fill"
        ptr:ptrMode="both"
        ptr:ptrDrawable="@drawable/default_ptr_rotate" /> -->

</RelativeLayout>

 

//---------------一下是gridview的条目的布局文件    叫:fenlei_item_gridview----------------------

<?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="wrap_content"
        android:id="@+id/tv_fenlei_grid_goods_name"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        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>

 

 

//-------------------一下是bean包中的FenLeiGoods类,封装类商品的属性---------------------------

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;



        }
}

 

//----------=============以下是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.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;

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.Toast;

public class MainActivity extends Activity {
    //数据网址
    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;
    //PullToRefreshGridView
    private PullToRefreshGridView gv_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);
                    gv_gridview.setAdapter(adapter);
                }else{
                    adapter.notifyDataSetChanged();
                }
                
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

//-------------------onCreate中---------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找到控件
        gv_gridview = (PullToRefreshGridView) findViewById(R.id.gv_gridview);      
        //获得网络数据
        huodeshuju();
        //设置gridview的模式
        gv_gridview.setMode(Mode.BOTH);
        //设置刷新监听
        gv_gridview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {

            @Override//下拉刷新
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                
                Toast.makeText(MainActivity.this, "下拉刷新", 0).show();
                //重新获得数据
                huodeshuju();
                //刷新适配器
                adapter.notifyDataSetChanged();
                //调用完成刷新的方法
                new FinishRefresh().execute();
                
                
            }

            @Override//上拉加载
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
                
                Toast.makeText(MainActivity.this, "上拉加载", 0).show();
                //重新获得数据
                huodeshuju();
                //刷新适配器
                adapter.notifyDataSetChanged();
                //调用完成刷新的方法
                new FinishRefresh().execute();
                
            }
        });
        
    }
 //-----------------------------------
  //完成刷新的方法
    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){
            //刷新完成
            gv_gridview.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();
                         Message message=new Message();
                         message.what=0;
                         message.obj=str;
                         handler.sendMessage(message);
                     }

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

             }
         }.start();

     }


    
    
}
//----------=============以上是MainActivity中======================

posted on 2016-09-29 13:31  巫山老妖  阅读(470)  评论(0编辑  收藏  举报