I'm trying to write a horizontal datepicker using Tabs with ViewPager2 and came across TabLayoutMediator. It seems like the perfect solution for what I am trying to accomplish but when I call attach() on the TabLayouMediator, it will lock the main thread, for 40 or 50ms in this case, if there are enough tabs. Is there any way around this? I was hoping that it would only load and create tabs that are visible, but it appears to loop over all the items and instantiate tabs for every one.
Here's a basic example:
...
val viewPagerAdapter = DemoCollectionAdapter(this)
val tabLayout = binding.tabLayout
val viewPager = binding.viewPager
viewPager.adapter = viewPagerAdapter
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = position.toString()
}.attach()
...
class DemoCollectionAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
override fun getItemCount(): Int = 1000
override fun createFragment(position: Int): Fragment {
val fragment = DemoObjectFragment()
fragment.arguments = Bundle().apply {
putInt("arg", position + 1)
}
return fragment
}
}
class DemoObjectFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding = DailyBinding.inflate(inflater, container, false)
binding.positionTextView.text = requireArguments().getInt("arg").toString()
return binding.root
}
}
In the documentation for swipe views (https://developer.android.com/guide/navigation/navigation-swipe-view-2#add_tabs_using_a_tablayout), it says you can have an infinite number of tabs, but it seems odd that this would lock the main thread trying to create them.
Any help would be appreciated on how to accomplish this!
I ended up using two viewpagers that worked together to solve this