欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PullToRefresh上拉加载和下拉刷新

程序员文章站 2024-03-17 11:51:16
...

1—添加依赖

implementation ‘com.github.userswlwork:pull-to-refresh:1.0.0’
implementation ‘com.google.code.gson:gson:2.8.5’

2— 添加权限

3—添加布局

<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/plv"
android:layout_width=“match_parent”
android:layout_height=“match_parent”
/>

4.MainActivity

public class MainActivity extends AppCompatActivity {
String urlString = “http://api.expoon.com/AppNews/getNewsList/type/1/p/1”;
private PullToRefreshListView plv;
ArrayList list=new ArrayList<>();
private ArrayAdapter madapter;
int page=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
plv = findViewById(R.id.plv);
//上下拉都支持
plv.setMode(PullToRefreshBase.Mode.BOTH);
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) {
    String murl=urlString+page;
    new MAsyncTask().execute(murl);
}

private 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> data = product.getData();

        ArrayList<String> strlist=new ArrayList<String>();
        for (int i = 0; i < data.size(); i++) {
            strlist.add(data.get(i).getNews_title());
        }
        list.addAll(strlist);
        madapter.notifyDataSetChanged();
        plv.onRefreshComplete();//让刷新头和刷新底部返回

    }
}

}