1. 程式人生 > >PullToRefreshListView上下拉重新整理

PullToRefreshListView上下拉重新整理

首先新增依賴

compile 'com.github.userswlwork:pull-to-refresh:1.0.0'
public class Fragment01 extends Fragment {

    private PullToRefreshListView plv;
    private List<RequestData.NewslistBean> data = new ArrayList<>();
    private int pageType=10;
    private int pageIndex=1;
private String urlpath
="http://api.tianapi.com/mobile/?key=71e58b5b2f930eaf1f937407acde08fe&num="+pageIndex; private MyAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment01
, container, false); plv = view.findViewById(R.id.plv); //初始化PullToRefreshListView initplv(); requestNetData(); return view; } private void requestNetData() { new MyTask().execute(urlpath); } private void initplv() { plv.setMode(PullToRefreshBase.Mode.BOTH
); plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) { pageIndex=10; pageType=1; urlpath="http://api.tianapi.com/mobile/?key=71e58b5b2f930eaf1f937407acde08fe&num="+pageIndex; requestNetData(); } @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) { pageIndex=pageIndex+10; pageType=2; urlpath="http://api.tianapi.com/mobile/?key=71e58b5b2f930eaf1f937407acde08fe&num="+pageIndex; requestNetData(); } }); } private String toJson(InputStream inputStream) { StringBuilder builder = new StringBuilder(); String string; InputStreamReader in = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(in); try { while ((string=reader.readLine())!=null){ builder.append(string); } } catch (Exception e) { e.printStackTrace(); } return builder.toString(); } class MyTask extends AsyncTask<String,Void,String> { @Override protected String doInBackground(String... strings) { String str=""; try { URL url = new URL(strings[0]); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); int responseCode = urlConnection.getResponseCode(); if (responseCode==200){ InputStream inputStream = urlConnection.getInputStream(); str=toJson(inputStream); } } catch (Exception e) { e.printStackTrace(); } return str; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); RequestData requestData = gson.fromJson(s, RequestData.class); List<RequestData.NewslistBean> newslist = requestData.getNewslist(); if (pageType==1){ data.clear(); } data.addAll(newslist); setlvadapter(); //關閉頭尾佈局 plv.onRefreshComplete(); } } private void setlvadapter() { if (adapter ==null){ adapter = new MyAdapter(data,getActivity()); plv.setAdapter(adapter); }else{ adapter.notifyDataSetChanged(); } } }