androidx1.10之后的fragment懒加载

用法

 val fragments = arrayListOf()
    fragments.add(Fragment1())
    fragments.add(Fragment2())
    fragments.add(Fragment3())
    fragments.add(Fragment4())

    viewPager.offscreenPageLimit = fragments.size - 1
    viewPager.adapter = object : FragmentStatePagerAdapter(
        supportFragmentManager,
        FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
    ) {
        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }

        override fun getCount(): Int {
            return fragments.size
        }

    }

初次进入的生命周期回调如下

Fragment1: onCreateView
Fragment1: onViewCreated
Fragment1: onStart
Fragment2: onCreateView
Fragment2: onViewCreated
Fragment2: onStart
Fragment3: onCreateView
Fragment3: onViewCreated
Fragment3: onStart
Fragment4: onCreateView
Fragment4: onViewCreated
Fragment4: onStart
Fragment1: onResume

返回主界面的生命周期回调如下

Fragment1: onPause
Fragment1: onStop
Fragment2: onStop
Fragment3: onStop
Fragment4: onStop

由主界面再次进入的生命周期回调如下

Fragment1: onStart
Fragment2: onStart
Fragment3: onStart
Fragment4: onStart
Fragment1: onResume

LazyFragment如下

    public abstract class LazyFragment extends Fragment {

private boolean isFirst; // 是否首次加载


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(getLayoutId(), container, false);
}


@LayoutRes
abstract int getLayoutId();

/**
 * 懒加载
 */
abstract void onLazyLoad();


@Override
public void onResume() {
    super.onResume();
    if (!isFirst) {
        initUiAndListener();
        onLazyLoad();
        isFirst = true;
    }

}

/**
 * 控件初始化和监听
 */
abstract void initUiAndListener();
}

写的比较简陋,大家将就看吧

你可能感兴趣的:(androidx1.10之后的fragment懒加载)