Tablayout with icons only

后端 未结 12 1410
暗喜
暗喜 2020-12-04 11:32

I am using design support to create tabs. I am also using ViewPager for swipable tabs.

Now, I don\'t know how to use only icons instead of texts in tabs

12条回答
  •  忘掉有多难
    2020-12-04 11:45

    As mentioned in the comments, defining the icons in the TabLayout does not work when using a PagerAdapter. For those using Kotlin, one workaround is to create an extension function like this:

    fun TabLayout.setupWithViewPagerAndKeepIcons(viewPager : ViewPager?) {
        val icons =  mutableListOf()
        repeat(tabCount) {
            icons.add(getTabAt(it)?.icon)
        }
        setupWithViewPager(viewPager)
    
        repeat(tabCount) {
            getTabAt(it)?.setIcon(icons.get(it))
        }
    }
    

    Then in the layout.xml add your icons to the TabLayout:

        
    
            
    
        
    

    Finally, use the extension function to setup the TabLayout with a ViewPager.

    tab_layout.setupWithViewPagerAndKeepIcons(view_pager)
    

提交回复
热议问题