TabLayout:set tabwidth取决于单个选项卡的文本大小

时间:2018-03-06 11:09:13

标签: android android-layout

我试图实现tablayout,我想根据各个标签中的文字内容设置标签的宽度,现在它设置相同,这导致小文本,标签宽度感觉更高。< / p>

3 个答案:

答案 0 :(得分:3)

试试这个:

public void wrapTabIndicatorToTitle(TabLayout tabLayout, int externalMargin, int internalMargin) {
    View tabStrip = tabLayout.getChildAt(0);
    if (tabStrip instanceof ViewGroup) {
        ViewGroup tabStripGroup = (ViewGroup) tabStrip;
        int childCount = ((ViewGroup) tabStrip).getChildCount();
        for (int i = 0; i < childCount; i++) {
            View tabView = tabStripGroup.getChildAt(i);
            //set minimum width to 0 for instead for small texts, indicator is not wrapped as expected
            tabView.setMinimumWidth(0);
            // set padding to 0 for wrapping indicator as title
            tabView.setPadding(0, tabView.getPaddingTop(), 0, tabView.getPaddingBottom());
            // setting custom margin between tabs
            if (tabView.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
                ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) tabView.getLayoutParams();
                if (i == 0) {
                    // left
                    settingMargin(layoutParams, externalMargin, internalMargin);
                } else if (i == childCount - 1) {
                    // right
                    settingMargin(layoutParams, internalMargin, externalMargin);
                } else {
                    // internal
                    settingMargin(layoutParams, internalMargin, internalMargin);
                }
            }
        }


        tabLayout.requestLayout();
    }
}

private void settingMargin(ViewGroup.MarginLayoutParams layoutParams, int start, int end) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        layoutParams.setMarginStart(start);
        layoutParams.setMarginEnd(end);
    } else {
        layoutParams.leftMargin = start;
        layoutParams.rightMargin = end;
    }
}

在java文件中设置视图寻呼机后添加:

wrapTabIndicatorToTitle(tabLayout,60,60);

答案 1 :(得分:1)

试试这个!它会减少你的努力。

<android.support.design.widget.TabLayout
        android:id="@+id/tblHome"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        app:tabMode="scrollable">

答案 2 :(得分:1)

将此代码放在TabLayout

的XML代码下面
<android.support.design.widget.TabLayout
        android:id="@+id/tab_Layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        app:tabGravity="fill"
        app:tabMode="scrollable"
        />