PullToRefresh下拉和上拉简单实现

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;

public class MainActivity extends AppCompatActivity {

    private String urlString="http://api.expoon.com/AppNews/getNewsList/type/1/p/";
    private String urlString1="http://www.93.gov.cn/93app/data.do?channelId=0&startNum=";
    private int page;
    private PullToRefreshListView listView;
    private List list=new ArrayList();
    private ArrayAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (PullToRefreshListView) findViewById(R.id.ptr_listview);
        listView.setMode(PullToRefreshBase.Mode.BOTH);//BOTH 设置支持上下拉
        mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
        listView.setAdapter(mAdapter);
        getNetData(0);

        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase pullToRefreshBase) {
                list.clear();
                getNetData(0);
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase pullToRefreshBase) {
                page++;
                getNetData(page);
            }
        });
    }

    private void getNetData(int page) {
        new MyAsyncTask().execute(urlString+page);
    }

    class MyAsyncTask extends AsyncTask{
        @Override
        protected String doInBackground(String... strings) {
            return NetUtil.getNetJson(strings[0]);
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            Product product = gson.fromJson(s, Product.class);
            for (int i = 0; i < product.getData().size(); i++) {
                list.add(product.getData().get(i).getNews_title());
            }
            mAdapter.notifyDataSetChanged();
            listView.onRefreshComplete();//让刷新头和刷新底部返回
        }
    }
}
pull-to-refresh 依赖   compile 'com.github.userswlwork:pull-to-refresh:1.0.0'

你可能感兴趣的:(PullToRefresh下拉和上拉简单实现)