关闭

Android上拉加载下拉刷新(使用第三方类库实现的)

标签: android之下拉刷新上拉加载第三方类库实现上拉加载下拉刷新
455人阅读 评论(0) 收藏 举报
package com.example.android_pullxml;


import java.util.ArrayList;
import java.util.List;


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


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.GridView;


import com.example.android_pullxml.adapter.MyListAdapter;
import com.example.android_pullxml.bean.HttpUtils;
import com.example.android_pullxml.bean.MyData.Datas;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;


public class TwoActivity extends Activity {
private PullToRefreshGridView gv;
private Handler handler = new Handler() {


@Override
public void handleMessage(Message msg) {
List<Datas> list1 = (List<Datas>) msg.obj;
if (msg.what == 0) {
for (Datas data : list1) {
listSum.add(0, data);
}
} else {
for (Datas data : list1) {
listSum.add(list1.size(), data);
}
}
adapter.notifyDataSetChanged();
gv.onRefreshComplete();
}


};
private MyListAdapter adapter;
private List<Datas> list;
private ArrayList<Datas> listSum;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
//
listSum = new ArrayList<Datas>();
gv = (PullToRefreshGridView) findViewById(R.id.ptrg);
gv.setMode(Mode.BOTH);
initData(0);
if (listSum != null) {


adapter = new MyListAdapter(TwoActivity.this, listSum);
gv.setAdapter(adapter);
}
gv.setOnRefreshListener(new OnRefreshListener2<GridView>() {


@Override
public void onPullDownToRefresh(
PullToRefreshBase<GridView> refreshView) {
initData(0);
}


@Override
public void onPullUpToRefresh(
PullToRefreshBase<GridView> refreshView) {
initData(1);
}
});
}


/**
* isflag为0时则让他下拉刷新,为1时则让他上拉加载
* */
private void initData(final int isflag) {


new Thread() {


@Override
public void run() {
super.run();
String json = HttpUtils
.getJson("http://apis.juhe.cn/goodbook/query?key=bfd6d2b411ee7f32b8c7b04a30901220&catalog_id="
+ getIntent().getStringExtra("catalog_id")
+ "&rn=10");
try {
JSONObject obj = new JSONObject(json);
JSONObject object = obj.getJSONObject("result");


JSONArray array = object.getJSONArray("data");
Gson gs = new Gson();
list = gs.fromJson(array.toString(),
new TypeToken<List<Datas>>() {
}.getType());
Message msg = Message.obtain();
msg.obj = list;
msg.what = isflag;
handler.sendMessage(msg);
} catch (JSONException e) {
e.printStackTrace();
}


}


}.start();
}
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:36623次
    • 积分:592
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:19篇
    • 译文:0篇
    • 评论:4条
    最新评论