您的位置:首页 > 其它

如何防止viewPager中Fragment预加载

2017-08-21 13:46 369 查看
viewPager+Fragment使我们开发中经常使用到的一个组合,当加载FristFragment时,如果你在Frgament各个生命周期打出log,会发现你的SecondFragment其实也已经加载好了,随时准备变为可见,这是机制不能说是有问题,但是如果在这两个Fragment初始化时我们都需要访问网络接口,那么问题就来了,我们肯定是希望加载到当前Fragment时才去访问网络获取数据,而不是预先去访问;在这里记录下防止Fragment预加载的方法:

1.BaseFragment

各个Fragment继承BaseFragment

/** BaseFragment
* @author:holiday*/
public abstract class BaseFragment extends Fragment implements
View.OnClickListener, View.OnTouchListener {
private InputMethodManager mInputMethodManager;

protected boolean isVisible;//当前Fragment是否可见

protected abstract void lazyLoad();

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//可以在baseFragment对键盘做处理
view.setOnTouchListener(this);
mInputMethodManager =
(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
}
//Fragment变为可见或不见时调用
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint()) {
isVisible = true;
lazyLoad();
} else {
isVisible = false;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
mInputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
return false;
}

@Override
public void onClick(View v) {
mInputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
}


2.每个Fragment都需要继承BaseFragment

下面举例说明firstFragment

public class FristFragment extends BaseFragment{
private View mView;
private boolean isPrepare;//标志位,标志是否已经初始化完成
private Context mContext;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.layout_fragment_first, null);
return mView;
}
@Override
protected void lazyLoad() {
if (isPrepare && isVisible) {
//TODO 类似网络请求任务、只有现实当前Fragment才可以执行的任务等

}
}

@Override
public void onPause() {
super.onPause();
isPrepare = false;
}

@Override
public void onResume() {
super.onResume();
isPrepare = true;
}
}


以上,如果更好方法,还请指出~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息