TabLayout与ViewPager2配合使用

(代码不完整,但都是关键代码,备忘使用)

ViewPager2 页面滚动状态改变回调处理,和TabLayout 联动

    private val onPageChangeCallback = object: ViewPager2.OnPageChangeCallback(){

        override fun onPageScrollStateChanged(state: Int) {

        }

        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
            tabLayout.setScrollPosition(position, positionOffset,
                true, true)
        }

        override fun onPageSelected(position: Int) {
            tabLayout.selectTab(tabLayout.getTabAt(position))
        }
    }

Tab 状态回调,和 ViewPager 联动

	private val onTabSelectedListener = object: TabLayout.OnTabSelectedListener{

        override fun onTabReselected(tab: TabLayout.Tab?) {

        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {

        }

        override fun onTabSelected(tab: TabLayout.Tab?) {
            tab?.apply {
                viewPager.setCurrentItem(position, true)
            }
        }

    }

Activity 创建时配置viewPager 和 TabLayout

  • PagerAdapter 为自定义的 FragmentStateAdapter
  • statusList 为Tab、Fragment 的构建数据
	override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sample)
        
		viewPager.adapter = PagerAdapter(this, statusList)
        viewPager.offscreenPageLimit = 3
        viewPager.registerOnPageChangeCallback(onPageChangeCallback)
        
		statusList.forEach {m->
        	tabLayout.addTab(tabLayout.newTab().setText(m.text))
        }        
        tabLayout.addOnTabSelectedListener(onTabSelectedListener)
	}

Activity 销毁时,注销ViewPager的回调

	override fun onDestroy() {
        super.onDestroy()
        viewPager.unregisterOnPageChangeCallback(onPageChangeCallback)
    }

你可能感兴趣的:(开发)