Android Fragment懒加载解决方式~(ViewPager+BottomNavigationView)

最新在开发新项目,框架搭建过程中。遇到fragment懒加载问题,项目中使用了ViewPager+BottomNavigationView的Ui来完成。接下来我来介绍下我是如何解决Fragment懒加载的。

正文:

首先来看xml文件

   

    

接下来初始化数据

    var mFragmentList: ArrayList = ArrayList()
    var mtitleList: ArrayList = ArrayList()

   //初始化数据
        val bookClassifyFragment: BookClassifyFragment = BookClassifyFragment()
        val bookCityFragment: BookCityFragment = BookCityFragment()
        val bookrackFragment: BookRackFragment = BookRackFragment()
        val myFragment: MyFragment = MyFragment()
        mFragmentList.add(bookClassifyFragment)
        mFragmentList.add(bookCityFragment)
        mFragmentList.add(bookrackFragment)
        mFragmentList.add(myFragment)
        mtitleList.add(resources.getString(R.string.bookrack))
        mtitleList.add(resources.getString(R.string.book_city))
        mtitleList.add(resources.getString(R.string.book_classify))
        mtitleList.add(resources.getString(R.string.user))

创建ViewPager需要的Adapter

public class BookCityFragmentStatePagerAdapter extends PagerAdapter {

    private List fragmentList;
    private List titleList;
    private FragmentManager manager;

    public BookCityFragmentStatePagerAdapter(List fragmentList, List titleList, FragmentManager fm) {
        super();
        this.fragmentList = fragmentList;
        this.titleList = titleList;
        this.manager = fm;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = fragmentList.get(position);
        //判断当前的fragment是否已经被添加进入Fragmentanager管理器中
        if (!fragment.isAdded()) {
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(fragment, fragment.getClass().getSimpleName());
            //不保存系统参数,自己控制加载的参数
            transaction.commitAllowingStateLoss();
            //手动调用,立刻加载Fragment片段
            manager.executePendingTransactions();
        }
        if (fragment.getView().getParent() == null) {
            //添加布局
            container.addView(fragment.getView());
        }
        return fragment.getView();
    }


    @Override
    public int getCount() {
        return titleList.size();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //移除布局
        container.removeView(fragmentList.get(position).getView());
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titleList.get(position);
    }
}

这里是最重要的地方

  if (!fragment.isAdded()) {
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.add(fragment, fragment.getClass().getSimpleName());
            //不保存系统参数,自己控制加载的参数
            transaction.commitAllowingStateLoss();
            //手动调用,立刻加载Fragment片段
            manager.executePendingTransactions();
        }
        if (fragment.getView().getParent() == null) {
            //添加布局
            container.addView(fragment.getView());
        }

接下来绑定数据,将刚创建的adpter的绑定到ViewPager上。
通过ViewPager.addOnPageChangeListener为每次点击的时候来设置BottomNavigationView选中状态。
通过BottomNavigationView.setOnNavigationItemSelectedListener方法来选择每次点击的menu时ViewPager的页面显示位置。

 val bookcitAdapter = BookCityFragmentStatePagerAdapter(
            mFragmentList,
            mtitleList,
            getSupportFragmentManager()
        )
        viewBinding.vpMian.adapter = bookcitAdapter
        //ViewPager绑定视图
        viewBinding.vpMian.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                viewBinding.bottomnavMain.menu.getItem(position).isChecked = true
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        //禁止ViewPager滑动
        viewBinding.vpMian.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                return true
            }
        })


        viewBinding.bottomnavMain.setOnNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.navigation_bookrack -> {

                    viewBinding.vpMian.currentItem = 0
                }

                R.id.navigation_book_city -> {
                    viewBinding.vpMian.currentItem = 1
                }
                R.id.navigation_book_classify -> {
                    viewBinding.vpMian.currentItem = 2
                }
                R.id.navigation_my -> {
                    viewBinding.vpMian.currentItem = 3
                }
            }
            true
        }

至此结束,各位喜欢的话可以点点关注~

你可能感兴趣的:(Android Fragment懒加载解决方式~(ViewPager+BottomNavigationView))