Search code examples
androidkotlinandroid-viewpager2

Same fragment creating on sliding in ViewPager2


I have 2 fragments that I want to show in my viewpager2 but only one shows in the view pager in both the tabs even though I am passing two fragments in my adapter although titles that I set are visible correctly.

Currently I am using viewpager2 with collapsing toolbar

ParentFragment

class MessagesFragment : Fragment() {

    private lateinit var binding: FragmentMessagesBinding
    private lateinit var adapter:ViewPager2Adapter


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View {
//        context?.theme?.applyStyle(R.style.ViewPagerTheme, true);
        binding = FragmentMessagesBinding.inflate(inflater, container, false)

        val fm: FragmentManager? = activity?.supportFragmentManager

        adapter = fm?.let { ViewPager2Adapter(it, lifecycle) }!!
        binding.pager.adapter = adapter

        binding.tabLayout.addTab(binding.tabLayout.newTab().setText("First"));
        binding.tabLayout.addTab(binding.tabLayout.newTab().setText("Second"));
        binding.pager.setPageTransformer(ZoomOutPageTransformer())

        binding.tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                binding.pager.currentItem = tab.position
            }

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

        binding.pager.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                binding.tabLayout.selectTab(binding.tabLayout.getTabAt(position))
            }
        })
        
        return binding.root
    }


}

ViewPagerAdapter

class ViewPager2Adapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
    FragmentStateAdapter(fragmentManager, lifecycle) {

    override fun createFragment(position: Int): Fragment {

        when (position) {
            1 -> { return ViewpagerFragment() }
            2 -> {return ViewPagerFragment2() }
        }

        return ViewpagerFragment()

    }

    override fun getItemCount(): Int {
        return 2
    }
}

Solution

  • You need to change the when cases from 1, 2 to 0, 1, as positions are 0-based

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