Android Kotlin TabLayout+ViewPager2

方式1:动态添加

    private val fragments by lazy {
        listOf(HealthVideoFragment(), HealthPhotoFragment())
    }
    private val tabTitles by lazy {
        listOf(SysUtil.getString(R.string.zone_video), SysUtil.getString(R.string.zone_photo))
    }

    private fun initTabAndViewPager() {
        binding.viewPager.adapter = object :
            FragmentStateAdapter(this.requireActivity().supportFragmentManager, this.lifecycle) {
            override fun getItemCount(): Int {
                return fragments.size
            }

            override fun createFragment(position: Int): Fragment {
                return fragments[position]
            }

        }

        val tabLayoutMediator =
            TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
                tab.text = tabTitles[position]
            }
        tabLayoutMediator.attach()
    }

布局:

       

            

            
        

方式2:静态添加TabItem


    

        

        

    

监听tabLayout选中的选项,并作出处理,可以刷新RecycleView,动态切换Fragment等操作。

        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                when (tab?.position) {
                    0 -> {
                    }
                    1 -> {
                    }
                }
            }

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

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

        })

你可能感兴趣的:(android,kotlin,android,studio)