用法
val fragments = arrayListOf<Fragment>()
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
}
}
初次進(jìn)入的生命周期回調(diào)如下
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
返回主界面的生命周期回調(diào)如下
Fragment1: onPause
Fragment1: onStop
Fragment2: onStop
Fragment3: onStop
Fragment4: onStop
由主界面再次進(jìn)入的生命周期回調(diào)如下
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;
}
}
/**
* 控件初始化和監(jiān)聽
*/
abstract void initUiAndListener();
}