使用fragment懒加载可以让fragment在没有visible时不加载网络数据,具体生命周期如下:
当fragment不可见时:
E/BFragment: setUserVisibleHint方法执行了
E/BFragment: onInvisible
E/BFragment: onCreate方法执行了
E/BFragment: onCreateView方法执行了
E/BFragment: onStart方法执行了
E/BFragment: onResume方法执行了
当fragment由不可见变为可见时:
E/BFragment: setUserVisibleHint方法执行了
E/BFragment: onVisible
当fragment再次变为不可见时:
E/BFragment: setUserVisibleHint方法执行了
E/BFragment: onInvisible
E/AFragment: onVisible
可以在onVisible和onInvisible进行相关操作,最后贴上BFragment的代码:
public class BFragment extends Fragment {
ImageView img;
boolean isVisiable;
private static final String TAG = "BFragment";
public BFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
img = (ImageView) view.findViewById(R.id.img);
Log.e(TAG,"onCreateView方法执行了");
return view;
}
@Override
public void onStart() {
super.onStart();
Log.e(TAG,"onStart方法执行了");
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG,"onCreate方法执行了");
}
@Override
public void onResume() {
super.onResume();
Log.e(TAG,"onResume方法执行了");
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.e(TAG,"setUserVisibleHint方法执行了");
if(getUserVisibleHint()){
isVisiable = true;
onVisible();
}else{
isVisiable = false;
onInvisible();
}
}
private void onInvisible() {
Log.e(TAG,"onInvisible");
}
private void onVisible() {
Log.e(TAG, "onVisible");
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
img.setVisibility(View.VISIBLE);
}
});
}
}).start();
}
}