第一次写博客,不为什么只为记录自己看到觉得好东西
写过的项目基本都会用到ViewPager+Fragment,每次都会为页面的加载顺序烦躁,虽然Viewpager有预加载功能 setOffscreenPageLimit(),但是效果不是很理想。我想在某个Fragment处于可状态的时候在加载数据,最近在网上看到了一个方法:
写一个类 extend Frgment
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();
}
//查看这个fragment的可见状态
@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;
}
之后的Frgament 继承BasePageFragment 在fetchData()里面写网络请求的方法