Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use TabItem through TabLayout in Android

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?

like image 805
Amir Avatar asked Jun 01 '16 18:06

Amir


1 Answers

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

                }
            });
like image 174
Amir Avatar answered Oct 04 '22 01:10

Amir