关于多个fragment+tabhost+viewpager,多个网络请求优雅懒加载处理(每个fragment第一次请求玩数据,后面默认不再加载,除非用户主动刷新)
解决问题:
1.ViewPager的懒加载模式为了让切换更加流畅,但是会多预加载的Fragment需要的数据进行网络请求,当多个Fragment都存在大量数据的时候,容易因为队列中请求较多导致卡顿,也浪费流量。
2.频繁切换ViewPager造成过多的网络请求。
3.在UI还没有渲染完成的时候请求数据,导致空指针异常。
解决方案:抽象基类的创建
public abstract class BasePageFragment extends Fragment {
protected boolean isViewInitiated;
protected boolean isVisibleToUser;
protected boolean isDataInitiated;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@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();
}
public abstract void fetchData();
public boolean prepareFetchData() {
return prepareFetchData(false);
}
public boolean prepareFetchData(boolean forceUpdate) {
if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
fetchData();
isDataInitiated = true;
return true;
}
return false;
}
}
public class Item1Fragment extends BasePageFragment {
private XRecyclerView xRecyclerView;
private ItemAdapter adapter = null;
private List<TaskDetail> lists;
public Item1Fragment() {
}
private void initView(View view) {
xRecyclerView = view.findViewById(R.id.recyclerview);
xRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
initData();
adapter = new ItemAdapter(getContext(),lists);
xRecyclerView.setAdapter(adapter);
adapter.setOnClickItemListener(new ItemAdapter.OnClickItemListener() {
@Override
public void onClick(TaskDetail taskDetail) {
Intent intent = new Intent(getActivity(), TaskDetailsActivity.class);
switch (taskDetail.getType()){
case "1"://待派件
break;
case "2"://待回收
break;
case "3"://代送回执包
break;
}
startActivity(intent);
}
});
}
@Override
public void fetchData() {
initView(view)//初始化
mPresenter.getSendNumDate();//网络请求
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item1,null);
return view;
}
}
原文地址:https://blog.csdn.net/qq_20369621/article/details/91457606
网友评论