为平板电脑设置选项卡布局 tabmode 的最佳方法是什么?

what is the best way to set the tab layout tabmode for tablets?

我正在使用 Android 设计支持库中的 TabLayout。如何将 MODE_SCROLLABLE 与 GRAVITY_FILL 一起使用,使其在所有设备和方向上看起来都一样?

目前,如果我使用 MODE_SCROLLABLE,它在 7 英寸平板电脑上看起来不错,但在 10 英寸平板电脑上,标签向左对齐。我希望能够对所有尺寸使用 GRAVITY_FILL。

这是我的表格布局:

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="72dp"            
/>

我正在代码中设置模式

 tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

根据 TabLayout.GRAVITY_FILL documentation:

Gravity used to fill the TabLayout as much as possible. This option only takes effect when used with MODE_FIXED.

因此,通过将您的模式设置为 MODE_SCROLLABLE,制表符始终从起始边缘对齐 - MODE_SCROLLABLE 的平板电脑和手机之间的唯一区别是制表符的最小宽度,由tabs material design spec.

请注意,如果您想将视图设置为始终可滚动,您可以通过 XML 指定引力和选项卡模式:

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

我遇到了同样的问题

在我看来,没有简单的方法可以解决这个问题。 在FIX_MODE中,tablayout中的所有选项卡都基于最大项目具有相同的宽度。

而在 SCROLL_MODE 中,所有的标签都有自己的宽度。

所以解决方案有点复杂。

我想到了两个解决方案,第一个解决方案:给每个选项卡项目的文本一些空白 space 以使所有项目具有相同的宽度并同时填充屏幕。

另一种解决方案是在tablayout中使用customview,就像这个article中所说的,然后你可以手动设置项目宽度。

//to get phones width in dp
int w= (int)((Resources.getSystem().getDisplayMetrics().widthPixels)/Resources.getSystem().getDisplayMetrics().density);
//To check screen width is greater than approx total no of tabswidth 
//I have calculated tabswidth by setting mode scrollable in layout and trying in defferent phones i got space left in 384dp width phone and no space in 360dp width phone so i took 370
        if(w>370){
            tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
        }
    else
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

我使用了与 Jayesh 非常相似的解决方案,但是我的解决方案使用了选项卡的最小宽度,并根据它计算要使用的模式。这样您只需要知道选项卡可接受的最小尺寸是多少。如果它们都适合剩余空间,它会将它们拉伸以填满所有 space,如果太多,它将使它们成为最小宽度并切换到可滚动。

 DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
        //For some reason, setting minWidth in xml and then accessing it here doesn't work, returns 0
        int minWidth = 80;
        tabLayout.setMinimumWidth(minWidth);

        //If there are less tabs than needed to necessitate scrolling, set to fixed/fill
        if(tabLayout.getTabCount() < dpWidth/minWidth){
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
            tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        }else{
            //Otherwise, set to scrollable
            tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

        }

在xml中,Tablayout只有这些属性

<android.support.design.widget.TabLayout
    android:id="@+id/sliding_tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMaxWidth="0dp"
    />