上拉下拉

private String path = "http://www.xieast.com/api/news/news.php?page=";
private int index = 1;

private XListView xlistview;

private List<NewsBean.DataBean> list = new ArrayList<>();
private MyAdapter adapter;
private Context context;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment1, container, false);
    xlistview = v.findViewById(R.id.xlistView);
    initView();
    adapter = new MyAdapter(list,getActivity());
    xlistview.setAdapter(adapter);
    new MyTask().execute(path+index);
    xlistview.stopLoadMore();
    return v;
}

private void initView(){
    xlistview.setPullLoadEnable(true);
    xlistview.setXListViewListener(this);
}

//下拉刷新
@Override
public void onRefresh() {
    list.clear();
    new MyTask().execute(path);
    xlistview.stopRefresh();
}

//加载更多   上拉
@Override
public void onLoadMore() {
    new MyTask().execute(path+(++index));
    xlistview.stopLoadMore();
}

class MyTask extends AsyncTask<String, Void, ArrayList<NewsBean.DataBean>> {
    @Override
    protected ArrayList<NewsBean.DataBean> doInBackground(String... strings) {
        try {
            String s = HttpUtils.get(strings[0]);
            Gson gson = new Gson();
            NewsBean fromJson = gson.fromJson(s, NewsBean.class);
            return (ArrayList<NewsBean.DataBean>) fromJson.getData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<NewsBean.DataBean> dataBeans) {
        list.addAll(dataBeans);
        adapter.notifyDataSetChanged();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43654610/article/details/83928172