Adifyr
Adifyr

Reputation: 2679

Odd Android TabLayout Indicator Scrolling Bug

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?

Upvotes: 0

Views: 949

Answers (2)

Niroj Shr
Niroj Shr

Reputation: 157

AmpPagerAdapter(childFragmentManager)

I was having the same issue using the getSupportFragmentManager() As posted answer by @SynerFlow himself, that was the reason. My solution was using getChildFragmentManager() instead.

Thank you

Upvotes: 1

Adifyr
Adifyr

Reputation: 2679

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.

Upvotes: 0

Related Questions