6

Recently google added android.support.design.widget.TabItem in supportDesign as documentation said:

TabItem is a special 'view' which allows you to declare tab items for a TabLayout within a layout. 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.

But when I add TabItems to my TabLayout:

 <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>

Nothing displayed (in fact place of Tabs exist but Icon/Text not). Does any one knows How to use TabItem through xml?

Amir
  • 16,067
  • 10
  • 80
  • 119

2 Answers2

3

Based on this answer, TabItem with tabLayout.setupViewPager have conflict and Icons disappear. To make it work you should implement two methods like following and avoid using setupViewPager method:

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                pager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    tabLayout.getTabAt(position).select();
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
Community
  • 1
  • 1
Amir
  • 16,067
  • 10
  • 80
  • 119
  • 2
    Note that setOnTabSelectedListener is deprecated and you should use addOnTabSelectedListener as it is discussed [here](http://stackoverflow.com/a/38498882/1476228). – RobertoAllende Feb 27 '17 at 21:23
0

you should set these attributes for the TabItems

android:layout_width
android:layout_height

Cheers

SzabK
  • 75
  • 1
  • 7
  • I set this attrs ( in fact if you dont set them A.S gives you error) – Amir Jun 02 '16 at 12:36
  • Hmm..strange.In my case I use a RelativeLayout (it doesnt matter which layout you use) which contains the TabLayout and TabItems. I set these attrs and the icons and everything displays. I'm using 23.2.1 support library – SzabK Jun 03 '16 at 09:01
  • Can you put it in github? – Amir Jun 03 '16 at 11:29