有的时候,我们不希望FragmentPagerAdapter对所有Fragment做onResume操作。我的Fragment可能有网络请求,这时候如果都做了onResume,对网络资源是一种浪费。我们希望,只有在Fragment是可见的情况下,onResume才是有效的。可以这么做:
public abstract class BaseFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
}
...
...
@Override
public void onResume()
{
super.onResume();
if (!getUserVisibleHint())
{
return;
}
onRefresh();
}
@Override
public void setUserVisibleHint(boolean visible)
{
super.setUserVisibleHint(visible);
if (visible && isResumed())
{
//Only manually call onResume if fragment is already visible
//Otherwise allow natural fragment lifecycle to call onResume
onResume();
}
}
}