自定义 TabLayout,例如 Google Play 音乐应用

Custom TabLayout like Google Play Music app

我实现了 TabLayout to similiar Google Play Music 应用程序。

这是我的布局:

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

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

我处理 TabLayout 的代码:

private void init() {
    mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
    mTabLayout.addTab(mTabLayout.newTab().setText("Category 1"));
    mTabLayout.addTab(mTabLayout.newTab().setText("Category 2"));
    mTabLayout.addTab(mTabLayout.newTab().setText("Category 3"));
    mTabLayout.addTab(mTabLayout.newTab().setText("Category 4"));
    mTabLayout.addTab(mTabLayout.newTab().setText("Category 5"));
    mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
}

但结果是 TabLayout 左边没有边距:

我尝试了这个 但结果不如预期。我如何自定义 TabLayout,如 Google Play Music 应用程序,如上所示?

您应该对 TabLayout 使用 android:marginLeft

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

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

要为纵向和横向设置不同的边距,请在 values/dimens.xml 和 values-land/dimens.xml

处使用不同的值

更新:

使用边距会产生 space,即使在滚动选项卡时也是如此。所以使用填充,clipToPadding="false"

<android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="16dp"
            android:clipToPadding="false">

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