2

我正在将我的代码更改为 androidX,我曾经将片段存储在 viewpager 中,每个片段包含几个列表,现在我在使用 viewpager2 时遇到延迟加载问题,是否有一些来自谷歌的示例代码?

4

1 回答 1

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() 并将您的逻辑放入其中
于 2021-03-19T15:20:26.303 回答