如何讓TabLayout的Tab自動延展

如何讓TabLayout的Tab自動延展

情境

如何使用 ViewPager + TabLayout 講到如何操作一個 ViewPager + TabLayout
但是如果遇到平板的時候
卻會發生 Tab 太小的情況
這時候你會怎麼修正呢?

如下圖所示





程式碼說明

這邊其實只需要在 xml 上面進行一些調整
原本的 xml 長這樣

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

經過``app:tabGravity="fill"參數的調整就可以讓他自動延展

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.givemepass.tablayouttabwidthdemo.MainActivity">

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

結果如下圖