<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/plv"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.handmark.pulltorefresh.library.PullToRefreshListView>
/**
- 具体代码
*/
//添加依赖:
compile 'com.github.userswlwork:pull-to-refresh:1.0.0’
package com.lll.pulltorefersh;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.bwie.xlistviewlibrary.utils.NetWordUtils;
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;
public class MainActivity extends AppCompatActivity {
String baseUrl = "http://www.93.gov.cn/93app/data.do?channelId=0&startNum=1";
private ArrayList<String> list = new ArrayList<>();
private int page = 0;
private PullToRefreshListView plv;
private ArrayAdapter<String> mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找控件
plv = findViewById(R.id.plv);
//上下拉都支持
plv.setMode(PullToRefreshBase.Mode.BOTH);
//设置Adapter
mAdapter = new ArrayAdapter<String>(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 i) {
new MAsyTask().execute(baseUrl+page);
}
private class MAsyTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
String jsonString = NetWordUtils.getNetjson(strings[0]);
return jsonString;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//开始解析
Gson gson = new Gson();
Product product = gson.fromJson(s, Product.class);
List<Product.DataBean> data = product.getData();
//初始化一个空的字符串集合
ArrayList<String> Stringlist = new ArrayList<>();
for (int i =0; i<data.size(); i++){
Stringlist.add(data.get(i).getTITLE());
}
list.addAll(Stringlist);
mAdapter.notifyDataSetChanged();
plv.onRefreshComplete();//让刷新头和刷新底部返回
}
}
}