安卓Android

Android ViewPager+Fragment 懒加载方案

2022-03-16  本文已影响0人  没有了遇见

Fragment 懒加载介绍

日常项目中无可或缺的会用到ViewPager嵌套Fragment的操作,以及Fragment中再嵌套Fragment的这种复杂嵌套的操作.由于ViewPager的缓存机制就会加载多个Fragmen页面导致加载速度变慢,这个时候我们就用到了Fragment 懒加载操作了

效果.png

示例效果实现是基于 ViewPager+FragmentStatePagerAdapter+Fragment

image.png

方案:

懒加载效果


效果.gif

实现:

1. ViewPager的FragmentStatePagerAdapter()

package com.wu.material.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter


/**
 *
 * 作者:吴奎庆
 *
 * 时间:2021/11/13
 *
 * 用途:
 */


class FragmentAdapter(fragmentList:ArrayList<Fragment>,fm: FragmentManager): FragmentStatePagerAdapter (fm){

    var fragmentList=ArrayList<Fragment>()
    init {
        this.fragmentList=fragmentList
    }
    override fun getItem(position: Int): Fragment {
        return fragmentList.get(position)
    }

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

2. 懒加载Fragment的处理

2.1 懒加载Fragment的基类

package com.wu.material.fragment

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment


/**
 * @author wkq
 *
 * @date 2022年01月30日 14:09
 *
 *@des ViewPager+Fragment懒加载
 *
 */

// Fragment 完整生命周期:
// onAttach -> onCreate -> onCreatedView -> onActivityCreated ->
// onStart -> onResume ->
// onPause -> onStop ->
// onDestroyView -> onDestroy -> onDetach

abstract class ViewPagerLazyLoadingFragment : Fragment() {


    /**
     * 当前页面是否可见
     */
    private var isVisibleToUser = false

    private var isResume = false

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        Log.e("LazyLoadingFragment :", "onHiddenChanged()" + hidden)
    }


    /**
     * 懒加载执行的方法
     */

    abstract fun lazyLoad()

    override fun onAttach(context: Context) {
        super.onAttach(context)
        Log.e("LazyLoadingFragment :", "onAttach()")

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e("LazyLoadingFragment :", "onCreate()")
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.e("LazyLoadingFragment :", "onViewCreated()")

    }

    override fun onStart() {
        super.onStart()
        Log.e("LazyLoadingFragment :", "onStart()")

    }

    override fun onResume() {
        super.onResume()
        isResume = true
        if (isVisibleToUser) {
            lazyLoad()
        }
        Log.e("LazyLoadingFragment :", "onResume()")
    }

    /**
     * 是否用户可见
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        this.isVisibleToUser = isVisibleToUser

        if (isVisibleToUser && isResume) {
            lazyLoad()
        }
        Log.e("LazyLoadingFragment :", "setUserVisibleHint()" + isVisibleToUser)
    }


    override fun onPause() {
        super.onPause()
        isResume = false
        Log.e("LazyLoadingFragment :", "onPause()")
    }

    override fun onStop() {
        super.onStop()
        Log.e("LazyLoadingFragment :", "onStop()")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.e("LazyLoadingFragment :", "onDestroyView()")
    }

    override fun onDestroy() {
        super.onDestroy()
        isResume = false
        isVisibleToUser = false
        Log.e("LazyLoadingFragment :", "onDestroy()")
    }

    override fun onDetach() {
        super.onDetach()
        Log.e("LazyLoadingFragment :", "onDetach()")
    }

}

2.2 懒加载的Fragment

package com.wu.material.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.wu.material.R


/**
 * @author wkq
 *
 * @date 2022年01月30日 14:09
 *
 *@des 懒加载测试页面
 *
 */

class DemoLazyLoadFragment : ViewPagerLazyLoadingFragment() {

    companion object {
        fun newInstance(): DemoLazyLoadFragment {
            val args = Bundle()
            val fragment = DemoLazyLoadFragment()
            fragment.arguments = args
            return fragment
        }
    }


    override fun lazyLoad() {
        Log.e("DemoLazyLoadFragment :","加载数据")
        Toast.makeText(activity,"懒加载加载数据", Toast.LENGTH_SHORT).show()

    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.page_1, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }


}

3. 主要实现

package com.wu.material.activity

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.wu.material.R
import com.wu.material.adapter.FragmentAdapter
import com.wu.material.databinding.ActivityLazyLoadingBinding
import com.wu.material.fragment.*
import com.wu.material.widget.CustomTitleView
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator


/**
 * @author wkq
 *
 * @date 2022年03月16日 9:04
 *
 *@des
 *
 */

class LazyLoadingFragmentActivity : AppCompatActivity() {
    var binding: ActivityLazyLoadingBinding? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView<ActivityLazyLoadingBinding>(this, R.layout.activity_lazy_loading)
        initVp()
        initMagicIndicator()
    }

    private fun initMagicIndicator() {

        var mTitles = arrayOf("当前", "历史", "曾经", "未来")
        binding!!.magicIndicator.setBackgroundColor(Color.WHITE)
        val commonNavigator = CommonNavigator(this)
        commonNavigator.scrollPivotX = 0.35f
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return if (mTitles == null) 0 else mTitles.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val simplePagerTitleView = CustomTitleView(context)
                simplePagerTitleView.setText(mTitles.get(index))
                simplePagerTitleView.normalColor = Color.parseColor("#666666")
                simplePagerTitleView.selectedColor = Color.parseColor("#222222")
                simplePagerTitleView.setOnClickListener { binding!!.vpContent.setCurrentItem(index) }
                return simplePagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = LinePagerIndicator(context)
                indicator.mode = LinePagerIndicator.MODE_EXACTLY
                indicator.setColors(Color.parseColor("#3399FF"))
                indicator.setRoundRadius(5f)
                return indicator
            }
        }
        binding!!.vpContent.offscreenPageLimit
        binding!!.magicIndicator.navigator = commonNavigator
        ViewPagerHelper.bind(binding!!.magicIndicator, binding!!.vpContent)
    }

    private fun initVp() {
        var fragmentList = ArrayList<Fragment>()

        fragmentList.add(DemoLazyLoadFragment.newInstance())
        fragmentList.add(DemoFragment2.newInstance())
        fragmentList.add(DemoFragment3.newInstance())
        fragmentList.add(DemoFragment4.newInstance())
        var fragmentAdapter = FragmentAdapter(fragmentList, this.supportFragmentManager)
        this.binding!!.vpContent.adapter = fragmentAdapter

    }


}

总结

由ViewPager +FragmentStateAdapter+Fragment 实现复杂页面的嵌效果,基于Fragment的setUserVisibleHint()方法简单的实现了Fragment的懒加载效果

看都看了点个赞再走吧

源码

1.项目源码

上一篇下一篇

猜你喜欢

热点阅读