The TabLayout
documentation gives an example of nesting TabItem
directly inside TabLayout
like so:
<android.support.design.widget.TabLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<android.support.design.widget.TabItem
android:text="@string/tab_text"/>
<android.support.design.widget.TabItem
android:icon="@drawable/ic_android"/>
</android.support.design.widget.TabLayout>
But it gives no example of how this could be used in practice, and the documentation for TabItem says:
This view is not actually added to TabLayout, it is just a dummy which allows setting of a tab items's text, icon and custom layout.
So what is TabItem
for? After extensive Googling, I cannot find a single example of anyone defining TabItems in XML. Is there any way to set up a tabbed activity using TabItem in the resource file as shown above?
Quick addition to @Mikes very helpful answer:
Android Studio now has a Template on how to use a
TabLayout
withTabItem
setup in an XML layout. Create all needed files with "New > Activity > Tabbed Activity" and choose "Action Bar Tabs(with ViewPager)" as shown in the screenshot:If you want to adjust the look of the
TabItem
without a custom view: use white vector assets as tabandroid:icon
and tint them with a selector (providing different colors based onandroid:state_selected
)The color of the line under the currently selected tab is set as
app:tabIndicatorColor
on tagTabLayout
.It took me a while to get it to work, so the complete steps turned into such a long answer that I don't want to copy them here. You can find my more detailed answer with full code at:
https://stackoverflow.com/a/49603559/414581
This appears to be a relatively recent addition to the design library, apparently added in version 23.2.0, though it's not mentioned in the revision history. It's functionality is pretty basic, and the only attributes it seems to use are the three given in its docs:
text
,icon
, andlayout
.From testing, it seems it's basically an XML shortcut for creating a new
Tab
, and setting its text, icon, and customView
, as one would usually do in code. When it says "This view is not actually added to TabLayout", I believe it's meant to suggest that it's not aView
in the regular sense, in that you can't set any kind of standard layout attribute on it, likelayout_width
orbackground
. It simply serves to cause theTabLayout
to create a newTab
for eachTabItem
, and callsetText()
,setIcon()
, andsetCustomView()
accordingly.For example, to add a
Tab
in code, we would usually do something like this:Whereas now we can replace everything after the comment above by adding a
TabItem
in the layout.Do note that the same requirements for the custom
View
layout still apply. That is, theTextView
for the text must have the system Resource ID@android:id/text1
, and theImageView
for the icon must have the ID@android:id/icon
. As an example, theR.layout.tab
from above: