Search code examples
androidandroid-tablayout

make Scrollable or fixed mode in Tablayout for dynamic number of Tabs


I want tabMode scrollable with tabFilled with tabs(having single line title). As number of Tab and their title is dynamic in my app. How could I handle them when I set given property. Title of tabs come's in two lines.when number of tab is greater.

    app:tabGravity="fill"
    app:tabMaxWidth="0dp"
    app:tabMode="fixed"

enter image description here

and when number of tabs are less and tabMode is set to scrollable. then extra space shown like below. enter image description here

how could I make a Tablayout to work in all phones and with one line text . Simply remove spaces for second screen and make single line for 1st Image.

I know I have to change it's tabMode and tabGravity for these two cases but How could I know when to change it's tabMode and tabGravity. It may be a case that I have only three tab's but their title are long and they are filling entire space. and some time we have 5 tabs with little title . They easily fit's in screen.


Solution

  • I come up with a new and better solution..

    List<String> titleTabs = getTitleOfTab();
            for (String module : titleTabs) {
                mTabLayout.addTab(mTabLayout.newTab().setText(module));  
            }
    
            mTabLayout.post(new Runnable()
            {
                @Override
                public void run()
                {
                    // don't forget to add Tab first before measuring..
                    DisplayMetrics displayMetrics = new DisplayMetrics();
                    ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                    int widthS = displayMetrics.widthPixels;
                    mTabLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                    int widthT = mTabLayout.getMeasuredWidth();
    
                    if (widthS > widthT) {
                        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
                        mTabLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                LinearLayout.LayoutParams.WRAP_CONTENT));
                    }
                }
            });
    

    where tablayout in xml must have tabGravity Fill and tabMode to Scrollable

    <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:minHeight="?attr/actionBarSize"
            app:tabGravity="fill"
            app:tabIndicatorHeight="4dp"
            app:tabMode="scrollable"/>