public class LazyBaseFragment extends BasePermissionFragment {
private boolean mHasLoadedOnce = false;
//子类重写该方法 进行懒加载
public void onLazyLoad() {
}
private boolean isLazy;
/**
* 请用viewPager第1个fragment 调用
*/
public LazyBaseFragment startLazyMode() {
isLazy = true;
return this;
}
//这个方法会多次调用 在onAttach之前 调用两次setUserVisibleHint(false) setUserVisibleHint(true) 显示隐藏的时候
也就是 fragment切换的时候 都会调用 当切走的时候 setUserVisibleHint(false) 当切回来的时候 setUserVisibleHint(true)
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
//this.isVisible 一定要写 不然 在onCreate之前调用 如果有实用当前fragment 中 view 会报空指针
Return true if the fragment is currently visible to the user. This means
* it: (1) has been added, (2) has its view attached to the window, and
* (3) is not hidden.
if (
this.isVisible()) {
if (isVisibleToUser && !mHasLoadedOnce) {
mHasLoadedOnce = true;
onLazyLoad();
}
}
super.setUserVisibleHint(isVisibleToUser);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
if (isLazy)
setUserVisibleHint(isLazy);
super.onActivityCreated(savedInstanceState);
}}