我将代码更改为androidX,我曾经将片段存储在viewpager中,并且每个片段都包含多个列表,现在我在使用viewpager2时存在关于延迟加载的问题,是否有Google提供的示例代码?
答案 0 :(得分:0)
试试这个
abstract class LazyFragment : Fragment() {
private var isInitData : Boolean = false // flag bit to determine whether the data is initialized
private var isVisibleToUser : Boolean = false // flags to determine whether fragments are visible
private var isPrepareView : Boolean = false // flag bit to determine that view has been loaded to avoid null pointer operations
override fun onViewCreated(@NonNull view: View, @Nullable savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
isPrepareView = true // At this point the view has been loaded and set to true
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
if (!hidden) {
lazyInitData()
}
}
override fun onResume() {
super.onResume()
isVisibleToUser = true
lazyInitData() // Load lazily
}
override fun onPause() {
super.onPause()
isVisibleToUser = false
}
override fun onAttach(context: Context) {
super.onAttach(context)
lazyInitData() // Load lazily
}
//
/**
* Lazy Loading Method
*/
private fun lazyInitData(){
if(setFragmentTarget()){
if(!isInitData && isVisibleToUser && isPrepareView) {
loadData()
}
}else {
if(!isInitData && isVisibleToUser && isPrepareView) {
loadData()
}else if (!isInitData && parentFragment ==null && isPrepareView ){
loadData()
}
}
}
private fun loadData() {
initData(); // Load data
isInitData = true; // Has the data flag been loaded and reassigned to true
}
/**
* Method of loading data, implemented by subclasses
*/
abstract fun initData()
/**
* Setting Fragment target, implemented by subclasses
*/
abstract fun setFragmentTarget(): Boolean
你需要做的是这个
(对于你在 ViewPager2 中使用的每个片段,让片段扩展 LazyFragment):