ViewPager專項練習(一)
阿新 • • 發佈:2018-12-12
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<Newsbean.NewslistBean> 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<Newsbean.NewslistBean> list1 = newsbean.getNewslist(); list.addAll(list1); adapter.notifyDataSetChanged(); listView.stopLoadMore(); break; } } @Override public void loadError(String error) { } }); }
}