在 Tablayout 中设置可滚动或固定模式以实现动态选项卡数量

2024-02-06

我想要 tab 模式可使用选项卡滚动填充选项卡(具有单行标题)。由于选项卡的数量及其标题是动态的在我的应用程序中。我该如何处理他们 当我设置给定的属性时。当选项卡数量较多时,选项卡标题分为两行。

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

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

我怎样才能制作一个可以在所有手机上使用一行文本的 Tablayout 。 只需删除第二个屏幕的空格并为第一个图像制作单行即可。

我知道我必须change it's tabMode and tabGravity for these two cases但我怎么知道何时更改它的 tabMode 和 tabGravity。可能我只有三个选项卡,但它们的标题很长并且填满了整个空间。有时我们有 5 个带有小标题的选项卡。它们很容易适合屏幕。


我想出了一个新的更好的解决方案..

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));
                }
            }
        });

xml 中的 tablayout 必须有tab重力填充 and tabMode 改为可滚动

<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"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Tablayout 中设置可滚动或固定模式以实现动态选项卡数量 的相关文章

随机推荐