I would like to make my TabLayout control grow in height to meet the height of tab with the the tallest custom view.
The simplest of layouts that has a TabLayout header:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMinWidth="96dp"
app:tabMode="scrollable" />
</LinearLayout>
And a layout for a simple image/text pair to be inflated for tab items:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/ic_launcher_background" />
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="false" />
</LinearLayout>
And the activity to populate the TabLayout control as follows:
class MainActivity : AppCompatActivity() {
lateinit var activityMainBinding : ActivityMainBinding
fun insertTab(s:String) {
val tab = activityMainBinding.tabLayout.newTab()
val item = ActivityItemBinding.inflate(layoutInflater)
item.tv.text = s
tab.customView = item.root
activityMainBinding.tabLayout.addTab(tab)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(activityMainBinding.root)
insertTab("Mark David John")
insertTab("Bob")
}
}
Despite all layout_height items above being wrap_content
, the TabView’s own height doesn’t reliably grow when items are added to it.
You can see above that “Mark David John” gets cut off.
Of course, using a minHeight
attribute in the TextView or setting a fixed height on the TabLayout itself works. But that presumes a priori knowledge of how big the names in the Tabs are going to be. With a fixed height solution, I’d have this:
That looks much better when fixed height sizes are used. But in the case where the “Mark David John” tab isn’t there, I’d have this:
When what I really want is to not have wasted blank space when it’s not needed:
Is there a solution that works to have the TabLayout grow in height to adjust to the height to accommodate the largest string or view?
Disclaimer: My real work application is using a custom view. The above is a sample, so switching to using non-custom views might not be viable.