I am writing an application where I use TabLayout
with ViewPager2
. Each tab has a fragment in the ViewPager
, the number of tabs may vary. I need to add a tab through the button located in the TabLayout
as a separate tab, which does not have a fragment.
I tried to find a way to trigger clicking on a tab without calling select()
, but I couldn’t. All the tips that I found advised to disable OnTabSelectedListener()
(which I use as a TabLayputMediator()
), but then I lose the tabs that are already working. I also saw a tip using OnTouchListener()
on a separate tab, but it requires calling view.performClick()
by default, which leads to a select(tab)
call.
Here’s the part of the code where I’m trying to do this:
binding.apply {
// Get data from room database
groupsViewModel.allGroups.observe(viewLifecycleOwner) { tasksGroups ->
tasksGroups?.let { groups = it }
tasksListContainerViewPager.adapter = TasksListViewPagerAdapter(requireActivity())
TabLayoutMediator(tabLayout, tasksListContainerViewPager) { tab, position ->
when (position) {
0 -> tab.setIcon(R.drawable.ic_star_fill_24)
else -> {
tab.text = groups[position - 1].groupTitle ?: "Group $position"
}
}
}.attach()
tasksListContainerViewPager.post {
tasksListContainerViewPager.setCurrentItem(1, false)
}
// That separate tab
val addGroupTab = tabLayout.newTab().setIcon(R.drawable.ic_add_24)
tabLayout.addTab(addGroupTab)
// FIXME: correct with warning (write my own separated OnSelectListener() ?)
addGroupTab.view.isClickable = false
addGroupTab.view.setOnTouchListener { _, _ ->
showCreateGroupBottomSheet()
false
}
}
}
Without this OnTouchListener()
, when clicking on the addGroup tab, TabLayout
will try to go to it, but since it does not have a fragment in the ViewPager
, it will go to the last existing tab, which is the expected behavior of TabLayoutMediator
, but not the desired behavior.
I also need my function to be called when clicking on this tab (which causes a dialog), while the content in the background remains the same.
I will be glad of any hints.
Константин Кручинин is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.