TabLayout 选项卡内的文本未居中

Text inside tabs of a TabLayout is not centered

我正在使用 TabLayout。我想让TabLayout填满全屏宽度,所以我加了app:tabGravity="fill"。我的问题是现在选项卡文本不居中。这是屏幕截图:

TabLayout的代码如下:

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar"
        app:tabMode="fixed"
        app:tabGravity="fill"
        app:tabTextColor="#d3d3d3"
        app:tabSelectedTextColor="#ffffff"
        app:tabIndicatorColor="#ff00ff"
        android:minHeight="?attr/actionBarSize"
        />

我看到了很多问题,但其中 none 解决了我的问题。非常感谢任何帮助。有关详细信息,我想告诉我正在尝试 。设备是 运行 Android 2.3.6 (API 10)。屏幕为 320x240。

将此添加到 xml 布局 android:gravity="center"

你可以参考这个了解更多详情

http://joshclemm.com/blog/?p=136

使用它来调整文本:

android:gravity="center" OR android:textAlignment="center"

您应该创建一个自定义选项卡..您正在为 tabLayout 使用这些属性,这将不起作用...您在上面提供的示例 link 使用名为 custom_tab.xml 的文件。使用它来定义您的 textView 并将这些属性放入其中。

默认情况下,如果您不使用另一种不居中的样式覆盖文本,则文本应居中。

如果您确定 Gravity="center" 不起作用,您也可以将自定义布局作为选项卡背景。所以你创建了一个相对布局,在它的中心有一个 textView 。 (这样你就可以自由地将想要的布局作为选项卡项)所以随意。

TabLayout tabLayout = (TabLayout)findViewById(R.id.tab_layout);
tabLayout.getTabAt(postion).setCustomView(resourceId);

希望对您有所帮助。

奇怪的是,Android Studio 中的预览显示选项卡标签居中,但在设备上它们是左对齐的。

正如其他答案所建议的那样,使用自定义视图是控制布局的好方法。

创建一个布局文件 layout/view_tab_label.xml,其中 TextView 的 ID @android:id/text1,因此您仍然可以在 TabItem:

中指定选项卡文本
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="@color/tab_label"
    android:gravity="center"/>

从选项卡项目(每个 TabItem 中的 android:layout 属性)引用此布局:

<android.support.design.widget.TabLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:tabIndicatorColor="@color/selected_tab"
    app:tabBackground="@color/tab_background">

    <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout="@layout/view_tab_label"
        android:text="@string/tab_1_title" />

    <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout="@layout/view_tab_label"
        android:text="@string/tab_2_title" />

</android.support.design.widget.TabLayout>

创建颜色资源文件color/tab_label.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/selected_tab" android:state_selected="true"/>
    <item android:color="@color/unselected_tab" android:state_selected="false"/>
</selector>

就这样做:-

       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:tabMaxWidth="0dp"
       app:tabGravity="fill"

我的问题是 TextView 没有在布局中居中。不是文本本身

所以。在 TextView 中。

android:layout_gravity="center"