使用ViewPager2时如何进行延迟加载?

时间:2019-04-17 11:20:02

标签: androidx android-viewpager2

我将代码更改为androidX,我曾经将片段存储在viewpager中,并且每个片段都包含多个列表,现在我在使用viewpager2时存在关于延迟加载的问题,是否有Google提供的示例代码?

1 个答案:

答案 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):

  1. 覆盖 onCreateView() 以增加布局
  2. 覆盖 setFragmentTarget (),它根据您是否希望立即或延迟加载该片段而返回 true 或 false
  3. 覆盖 initData() 并将您的逻辑放入其中