ViewPager专项练习(一)

public class Fragment1 extends Fragment {
private int page = 0;
private int type = 0;//加载的类型,
private XListView listView;
private MyAdapter adapter;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fg_layout, null);
    //初始化控件
    listView = view.findViewById(R.id.listview);
    //设置权限
    listView.setPullLoadEnable(true);
    listView.setPullRefreshEnable(true);
    listView.setXListViewListener(new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            type = 1;
            page = 0;
            getDataFromNet();
        }

        @Override
        public void onLoadMore() {
            type = 2;
            page++;
            getDataFromNet();
        }
    });
    //从网络获取数据

    return view;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        getDataFromNet();
    }
}

private void getDataFromNet() {
    //获取网络工具类
    HttpUtils httpUtils = HttpUtils.getHttpUtils();
    httpUtils.get(HttpConfigs.news_url + "&page=" + page);
    httpUtils.setOnHttpLoadListener(new HttpUtils.HttpLoadListener() {

        private List list;

        @Override
        public void loadSuccess(String json) {
            //使用Gson
            Gson gson = new Gson();
            Newsbean newsbean = gson.fromJson(json, Newsbean.class);
            switch (type) {
                case 0:
                    list = newsbean.getNewslist();
                    adapter = new MyAdapter(MyApp.getContext(), list);
                    listView.setAdapter(adapter);
                    break;
                case 1:
                    list = newsbean.getNewslist();
                    adapter = new MyAdapter(MyApp.getContext(), list);
                    listView.setAdapter(adapter);
                    listView.stopRefresh();
                    break;
                case 2:
                    List list1 = newsbean.getNewslist();
                    list.addAll(list1);
                    adapter.notifyDataSetChanged();
                    listView.stopLoadMore();
                    break;
            }
        }

        @Override
        public void loadError(String error) {

        }
    });


}

}

你可能感兴趣的:(工具类,接口回调)