//添加依赖:
compile 'com.github.userswlwork:pull-to-refresh:1.0.0'
//布局文件使用控件
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/plv"
android:layout_width="match_parent"
android:layout_height="match_parent"></com.handmark.pulltorefresh.library.PullToRefreshListView>
//具体代码
package com.wzq.pulltorefreshdemo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.util.ArrayList;
import java.util.List;
/**
* 接入PullToRefresh
* 1.引入Library
* 2.依赖model
* 3. 布局文件中使用可刷新的控件
* 4. 设置可刷新监听--> mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>()
* 设置可以上拉 mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
*/
public class MainActivity extends AppCompatActivity {
String baseUrl = "http://www.93.gov.cn/93app/data.do?channelId=0&startNum=";
private ArrayList<String> list = new ArrayList();
private PullToRefreshListView plv;
private int page = 0;
private ArrayAdapter<String> mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find
plv = (PullToRefreshListView) findViewById(R.id.plv);
plv.setMode(PullToRefreshBase.Mode.BOTH);//上下拉都支持;
// 设置adapter
mAdapter = new ArrayAdapter<>(MainActivity.this,
android.R.layout.simple_list_item_1, list);
plv.setAdapter(mAdapter);
//请求网络
getNetData(0);
//处理上拉和下拉的操作;
plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
// 下拉刷新
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
list.clear();
getNetData(0);
}
//上拉加载
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
page++;
getNetData(page);
}
});
}
private void getNetData(int page) {
new MAsyncTask().execute(baseUrl+page);
}
class MAsyncTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
return NetWordUtils.getNetjson(strings[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Gson gson = new Gson();
Product product = gson.fromJson(s, Product.class);
List<Product.DataBean> dataTemp = product.getData();
ArrayList<String> stringList = new ArrayList<>();//初始化一个空的字符串集合
for (int i = 0; i <dataTemp.size() ; i++) {
stringList.add(dataTemp.get(i).getTITLE());
}
list.addAll(stringList);
mAdapter.notifyDataSetChanged();
plv.onRefreshComplete(); // 让刷新头和刷新底部返回
}
}
}