如何将值传递给 viewPagerAdapter?

How to pass value to viewPagerAdapter?

根据我的代码,我正在尝试加载具有两种不同样式的 viewpager 适配器。我在这里根据 tabItemCount 设置制表符和位置字符串。我想在 viewpager 适配器中做同样的事情。我只是尝试 tabItemCountviewpageradapter 并根据值加载适配器。例如:如果 tabItemCount 为 2,则加载拖曳标签。如果是 3 个加载 3 个选项卡。这样我就不必使用两个不同的适配器。但是我无法将 tabItemCount 传递给 viewpageradapter。

MainFragment.kt

private fun initAdapters() {
            val tabItemCount: Int = if (viewModel.appointmentType == AppointmentType.FromHospitalAppointment) 3 else 2
            val adapter = MainViewPagerAdapter(
                childFragmentManager, viewLifecycleOwner.lifecycle, tabItemCount
            )
    
            binding.apply {
                viewPager2.adapter = adapter
    
                TabLayoutMediator(tabLayoutGetAppointmentStepSecond, viewPager2GetAppointmentStepSecond) { tab, position ->
                    if (tabItemCount == 2) {
                        when (position) {
                            0 -> tab.text = getString(R.string.asm_appointments_in_hospital)
                            1 -> tab.text = getString(R.string.asm_video_appointments)
                        }
                    } else {
                        when (position) {
                            0 -> tab.text = getString(R.string.asm_appointments_in_hospital)
                            1 -> tab.text = getString(R.string.asm_video_appointments)
                            2 -> tab.text = getString(R.string.asm_hospital)
                        }
                    }
    
                }.attach()
            }
        }

MainViewPagerAdapter.kt

class MainViewPagerAdapter(
    fragmentManager: FragmentManager, lifecycle: Lifecycle, tabItemCount
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    override fun getItemCount(): Int {
        return 3
    }

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> {
                MyProfileInformationASMFragment()
            }
            1 -> {
                MyProfilePersonInformationASMFragment()
            }

            2 -> {
                MyProfileHealthCardASMFragment()
            }
            else -> {
                Fragment()
            }
        }
    }
}

尝试像这样更改 MainViewPagerAdapter class 声明

class MainViewPagerAdapter(
    fragmentManager: FragmentManager, 
    lifecycle: Lifecycle, 
    val tabItemCount: Int
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    override fun getItemCount(): Int = tabItemCount

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> {
                MyProfileInformationASMFragment()
            }
            1 -> {
                MyProfilePersonInformationASMFragment()
            }

            2 -> {
                MyProfileHealthCardASMFragment()
            }
            else -> {
                Fragment()
            }
        }
    }
}