I am using TabLayout
with a ViewPager
in Android. Whenever I run the code, the TabLayout Indicator is behaving oddly. Instead of auto-snapping to the next tab, it's acting like a horizontal scrollbar. So I have a TabLayout Indicator that's literally hanging between two tabs. And there is no error. Here is my code:
My onCreate()
method:
val tabLayout = findViewById<TabLayout>(R.id.tl)
val viewPager = findViewById<ViewPager>(R.id.vp)
viewPager.adapter = AmpPagerAdapter(supportFragmentManager)
tabLayout.setupWithViewPager(viewPager)
val icons = arrayOf(R.drawable.ic_hot_24dp, R.drawable.ic_person_24dp)
icons.forEachIndexed { index, i -> tabLayout.getTabAt(index)?.setIcon(i) }
My FragmentPagerAdapter:
class AmpPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
private val pages = arrayListOf(Fragment(), Fragment())
override fun getItem(position: Int): Fragment = pages[position]
override fun getCount(): Int = pages.size
}
First I thought I added too many tabs, but that isn't the case as my Pages Array List length is 2. The Indicator works fine when I click on the tabs.
What's the issue?
Alright, so the issue was that I was filling the FragmentPagerAdapter
with the default Fragment class from Android, which has no layout attached to it. When I made my own fragment and inflated the layout, the TabLayout Indicator started working properly.
Note that the actual problem was that there was no layout inflated. And that's why filling in the default Fragment class was a problem.