package com.higher.lazyfragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public abstract class LazyFragment extends Fragment {
private View viewRoot;
private boolean isShow;
private boolean isLoaded;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
viewRoot = inflater.inflate(getLayoutId(), container, false);
initView(viewRoot);
if (!isShow && getUserVisibleHint()) {
dispatchVisibleHint(true);
}
return viewRoot;
}
protected abstract int getLayoutId();
protected abstract void initView(View viewRoot);
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (viewRoot != null) {
if (!isShow && isVisibleToUser) {
//当前从不可见变为可见
dispatchVisibleHint(true);
} else if (isShow && !isVisibleToUser) {
//当前从可见变为不可见
dispatchVisibleHint(false);
}
}
}
private void dispatchVisibleHint(boolean isVisible) {
isShow = isVisible;
if (isVisible) {
if (!isLoaded) {
Log.e(TAG, "开始加载" + getClass().getName());
isLoaded = true;
loadData();
}
} else {
Log.e(TAG, "停止加载" + getClass().getName());
stopLoadData();
}
}
protected void stopLoadData() {
}
protected void loadData() {
}
@Override
public void onDestroyView() {
super.onDestroyView();
viewRoot = null;
isShow = false;
isLoaded = false;
}
}
注意配合 viewpager.setOffscreenPageLimit();使用
分析 /** * 一: 1,FragmentPagerAdapter与FragmentStatePagerAdapter的区别 * 后者会销毁Fragment,只保留一个状态,前者不会真正的销毁。 * 内存开销大(Fragment多,内部数据多)的时候推荐使用后者 * 二:FragmentPagerAdapter * 2,推荐在getItem中创建Fragment * 3,FragmentPagerAdapter调用的五个函数 * adapter.startUpdate()---->adapter.instantiateItem()---->adapter.destroyItem()—>adapter.setPrimaryItem()---->adapter.finishUpdate() * startUpdate(): * instantiateItem():首先在FragmentManager中寻找Fragment找到了就attach,找不到会去getItem()中寻找Fragment,然后add * destroyItem():mCurTransaction.detach(fragment) * fragment.setUserVIsibileHint(false)在生命周期之前调用 * setPrimaryItem:fragment.setUserVIsibileHint(true) * finishUpdate():commitNowAllowingStateLoss() * 三:FragmentStatePagerAdapter * Fragment 会被remove(),FragmentPagerAdapter只会detach() */
|