实现fragment的懒加载,我的大体思路是:当fragment可见准备好数据的时候,显示当前的fragement。
首先我们来定义一个基本的fragment
/****
* 用于懒加载
*****/
public abstract class BaseFrament extends Fragment {
protected boolean isVisible;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
protected void onVisible(){
lazyLoadData();
}
public abstract void lazyLoadData();
protected void onInvisible(){}
}
在fragment中实现
public class MyOrderFragment extends BaseFrament implements AdapterView.OnItemClickListener {
//标志位 标志已经初始化完成
private boolean isPrepared;
@BindView(R.id.my_order_viewpager_listview)
XListView mMyOrderViewpagerListview;
private int pageIndex = 0;
private List<MyOrderBean> allList = new ArrayList<>();
private MyOrderListAdapter allListAdapter;
MyOrderBean order;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.viewpager_my_order, null);
ButterKnife.bind(this, view);
isPrepared = true;
lazyLoadData();
return view;
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Tools.toastTools(getActivity(),"点击了item");
if (i > 0) {
order = allList.get(i - 1);
}
Intent intent = new Intent(getActivity(), MyOrderDestActivity.class);
intent.putExtra("order", order);
startActivity(intent);
}
}
public void lazyLoadData() {
if (!isPrepared || !isVisible) {
return;
}
pageIndex = this.getArguments().getInt("pages");
if (allList.size() == 0) {
//未支付网络请求
requestOrder();
} else {
allListAdapter.notifyData(allList);
}
mMyOrderViewpagerListview.setOnItemClickListener(this);
}
/**
* 获取url
*/
public void getUrl(int index) {
switch (index) {
case 0:
//全部订单
orderUrl = ConfigAPI.MY_ORDER_URL + "memberId=" + userId + "&page=" + page;
break;
case 1:
//待付款
orderUrl = ConfigAPI.MY_ORDER_URL + "memberId=" + userId + "&page=" + page + "&payStatus=0";
break;
case 2:
//待发货
orderUrl = ConfigAPI.MY_ORDER_URL + "memberId=" + userId + "&page=" + page + "&shipStatus=0";
break;
case 3:
//已付款
orderUrl = ConfigAPI.MY_ORDER_URL + "memberId=" + userId + "&page=" + page + "&payStatus=1";
break;
}
}