/** * Fragment 加载网络请求 */ public abstract class BaseLoadDataForNetFragment extends Fragment { // 视图是否初始化完成 protected boolean isViewInitiated; // 界面是否可见 protected boolean isVisibleToUser; // 数据是否加载 protected boolean isDataInitiated; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); isViewInitiated = true; prepareFetchData(); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); this.isVisibleToUser = isVisibleToUser; prepareFetchData(); } private void prepareFetchData() { // 不设置为需要每次可见的时候都强制刷新界面 prepareFetchData(false); } /** * 设置true,可强制刷新界面 * * @param forceUpdate 是否强制刷新界面 * @return */ protected void prepareFetchData(boolean forceUpdate) { if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) { fetchDataForNet(); isDataInitiated = true; } } /** * 刷新数据,网络刷新数据 */ public abstract void fetchDataForNet(); }
fragment中请求网络。。
子fagnment 复用已经加载的数据
@Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { WLog.d("onCreateView"); View mView = inflater.inflate(R.layout.fragment_my_order, container, false); mNoDataTV = (TextView) mView.findViewById(R.id.fragment_order_tv_no_data); mShowLoading = (LinearLayout) mView.findViewById(R.id.fragment_order_ll_loading); // 子界面可以重用网络加载的数据 if (isDataInitiated) { WLog.d("数据已经加载过...无需再次请求数据"); //mShowLoading.setVisibility(View.GONE); //mNoDataTV.setVisibility(View.VISIBLE); } return mView; }