TabLayout not filling width when tabMode set to 'scrollable'

前端 未结 17 757
傲寒
傲寒 2020-12-02 16:58

I have added TabLayout (from support library v22.2.1) to my Fragment as:



        
17条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 17:36

    @dtx12 answer doesn't work if any tab title is bigger than (measuredWidth/ tabCount).

    There is my TabLayout subclass for this situation (in Kotlin). I hope this will help someone.

    class FullWidthTabLayout : TabLayout {
    
        constructor(context: Context?) : super(context)
    
        constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    
        constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    
        override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
            super.onLayout(changed, l, t, r, b)
            if (changed) {
                val widths = mutableListOf()
                for (i in 0..this.tabCount - 1) {
                    widths.add(this.getTabAt(i)!!.customView!!.width)
                }
    
                if (widths.sum() < this.measuredWidth) {
                    var equalPart: Long = this.measuredWidth.toLong() / this.tabCount.toLong()
                    var biggerWidths = widths.filter { it > equalPart }
                    var smallerWidths = widths.filter { it <= equalPart }
                    var rest: Long = this.measuredWidth.toLong() - biggerWidths.sum()
                    while (biggerWidths.size != 0) {
                        equalPart = rest / smallerWidths.size
                        biggerWidths = smallerWidths.filter { it >= equalPart }
                        smallerWidths = smallerWidths.filter { it < equalPart }
                        rest -= biggerWidths.sum()
                    }
                    val minWidth = (rest / smallerWidths.size) + 10 //dont know why there is small gap on the end, thats why +10
                    for (i in 0..this.tabCount - 1) {
                        this.getTabAt(i)!!.customView!!.minimumWidth = minWidth.toInt()
                    }
                }
            }
        }
    }
    

提交回复
热议问题