Material Design 之 TabLayout 使用

依然範特稀西發表於2016-12-29

寫在前面

更多Material Design 文章請看:
Material Design 之 Toolbar 開發實踐總結
Material Design之 AppbarLayout 開發實踐總結
Material Design 之 Behavior的使用和自定義Behavior

這是Material Design系列文章的第四篇,講一下專案中用得非常多的一個元件-Tabs,在一個app中,Tabs 使不同檢視和功能之間的切換變得簡單。使用 tabs 將大量關聯的資料或者選項劃分成更易理解的分組,可以在不需要切換出當先上下文的情況下,有效的進行內容導航和內容組織,便於使用者操作。提升使用者體驗。下面一起來看一下Tabs的使用。

Tabs 的使用方式

用法:tab 用來顯示有關聯的分組內容。tab標籤用來簡要的描述該Tab下的內容。

(1) 預設的app bar + 固定的tab bar

Material Design 之 TabLayout 使用
tabs1.png

(2)可擴充套件的app bar+ tab bar

Material Design 之 TabLayout 使用
tabs2.png

(3)隨著滾動內容被鎖定在頂部的ab bar

Material Design 之 TabLayout 使用
tabs3.png

(4)預設的app bar + 可滾動的app bar

Material Design 之 TabLayout 使用
tabs4.png

(5)和指示器一樣字型顏色的tabs

Material Design 之 TabLayout 使用
tabs5.png

(6)預設app bar +固定的帶圖示的 app bar

Material Design 之 TabLayout 使用
tabs6.png

(7) icon 顏色和指示器顏色一樣的tabs

Material Design 之 TabLayout 使用
tabs7.png

以上就是Material Design 官方給出的Tabs 的一些使用模式。基本上能涵蓋我們專案中的使用。

Tab特性:

  • Tabs 應該在一行內,如果有必要,標籤可以顯示兩行然後截斷
  • Tabs 不應該被巢狀,也就是說一個Tab的內容裡不應該包含另一組Tabs
  • Tabs 控制的顯示內容的定位要一致。
  • Tab 中當前可見內容要高亮顯示。
  • Tabs 應該歸類並且每組 tabs 中內容順序相連。
  • 一組 tabs 至少包含 2 個 tab 並且不多於 6 個 tab。

其他的一些使用細節和規範請檢視 Material Design 的官方文件。

Tabs 的具體實現-TabLayout

上面講了Tabs的一些特性、規範和使用模式,下面我們看一下具體在程式碼中的 實現。要實現一組Tabs,Google 給我提供了一個控制元件-TabLayout。來看一下TabLayout的介紹和使用。

TabLayout 提供一個水平方向的佈局來顯示Tabs,繼承的是HorizontalScrollView 這個類。

TabLayout 基礎
1,建立Tabs (程式碼中)

Tabs的顯示是通過TabLayout.Tab 來完成的,我們可以通過newTab() 來建立,在這兒你也可以改變Tab的標籤(label)和icon 通過 setText(int) 和setIcon(int)。最後需要通addTab(Tab ) 方法把Tab新增到TabLayout 顯示。程式碼如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/white"
        app:title="TabLayout示例"
        app:navigationIcon="@drawable/ic_book_list"
        >

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

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

</LinearLayout>複製程式碼

Activity 中新增Tab:

        mTabLayout = (TabLayout) findViewById(R.id.tab_layout2);

        mTabLayout.addTab(mTabLayout.newTab().setText("個性推薦"));
        mTabLayout.addTab(mTabLayout.newTab().setText("歌單"));
        mTabLayout.addTab(mTabLayout.newTab().setText("主播電臺"));
        mTabLayout.addTab(mTabLayout.newTab().setText("排行榜"));複製程式碼

效果圖如下:

Material Design 之 TabLayout 使用
simple_tabLayout.png

2,建立Tabs (xml 佈局檔案中)

直接在xml 新增Tab:
上面是在程式碼中通過addTab 新增Tab,也可以直接在 xml 中新增 ,使用TabItem,程式碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/white"
        app:title="TabLayout示例"
        app:navigationIcon="@drawable/ic_book_list"
        >

    </android.support.v7.widget.Toolbar>
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
         <android.support.design.widget.TabItem
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="個性推薦"
             />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="歌單"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="主播電臺"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="排行榜"
            />
    </android.support.design.widget.TabLayout>

</LinearLayout>複製程式碼

效果第一種方式是一樣的,就不再多講。

3,帶Icon的Tabs

建立Tab的時候是可以設定圖示的,可以在佈局檔案中用TabItem的icon屬性,程式碼如下:

 <android.support.design.widget.TabItem
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:text="個性推薦"
             android:icon="@drawable/ic_favorite_border_black_24dp"
             />複製程式碼

也可依在程式碼中設定:

mTabLayout.addTab(mTabLayout.newTab().setText("個性推薦").setIcon(R.drawable.ic_favorite_border_black_24dp));複製程式碼

效果如下:

Material Design 之 TabLayout 使用
tab_with_icon.png

當然了,還可是隻有Icon 的Tab,把設定的標籤去掉不讓顯示就好了,這裡就不多講了。

4,Tab 選中監聽

Tab切換的時候,我們需要切換頁面的內容,這時候就需要為它設定一個監聽器TabLayout.OnTabSelectedListener,如下:

 mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.i(TAG,"onTabSelected:"+tab.getText());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });複製程式碼

然後就可以在onTabSelected 做對應的邏輯處理了,切換到哪個Tab就顯示對應Tab 的內容。

TabLayout 進階

上面講到了TabLayout 最簡單的使用,實際專案中,我們的需求更復雜一些,比如:需要改變Tabs 的指示器的高和顏色,需要改變Tab的寬高,Tab的顏色,固定的Tabs,可滾動的Tabs ,Tabs+viewPager+Fragment 的使用等等。因此我們需要了解TabLayout的一些重要屬性。

  • app:tabBackground 設定Tabs的背景

  • app:tabGravity 為Tabs設定Gravity,有兩個常量值,GRAVITY_CENTER,GRAVITY_FILL,用法:

    app:tabGravity="center"複製程式碼

    或者

    app:tabGravity="fill"複製程式碼

    值為center,Tabs就居中顯示,fill 就充滿TabLayout 。

  • app:tabIndicatorColor 設定指示器的顏色(預設情況下指示器的顏色為colorAccent)

  • app:tabIndicatorHeight 設定指示器的高度,Material Design 規範建議是2dp

  • app:tabMaxWidth 設定 Tab 的最大寬度

  • app:tabMinWidth 設定 Tab 的最小寬度

  • app:tabMode 設定Tabs的顯示模式,有兩個常量值,MODE_FIXED,MODE_SCROLLABLE。用法:

    app:tabMode="fixed"複製程式碼

    或者

    app:tabMode="scrollable"複製程式碼

    fixed 表示固定的Tab,scrollable 可滾動的Tab, Tab個數少的時候用 fixed,當Tab個數較多(大於四個或者5個)時用scrollable。

  • app:tabPadding 這幾個很簡單設定Tab padding

  • app:tabPaddingTop
  • app:tabPaddingBottom
  • app:tabPaddingStart
  • app:tabPaddingEnd

  • app:tabSelectedTextColor 設定Tab選中後,文字顯示的顏色

  • app:tabTextColor 設定Tab未選中,文字顯示的顏色

以上就是TabLayout 的常用屬性,瞭解了這些屬性後我們就能做出更多的效果了。

可滾動的Tabs:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/white"
        app:title="TabLayout示例"
        app:navigationIcon="@drawable/ic_book_list"
        >

    </android.support.v7.widget.Toolbar>
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        app:tabIndicatorColor="@android:color/holo_red_light"
        app:tabIndicatorHeight="2dp"
        app:tabSelectedTextColor="@android:color/holo_red_light"

        >
         <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="個性推薦"
        android:icon="@drawable/ic_favorite_border_black_24dp"
        />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="歌單"
            android:icon="@drawable/ic_insert_photo_black_24dp"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="主播電臺"
            android:icon="@drawable/ic_play_circle_outline_black_24dp"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="排行榜"
            android:icon="@drawable/ic_clear_all_black_24dp"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="動態"
            android:icon="@drawable/ic_favorite_border_black_24dp"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="聽歌識曲"
            android:icon="@drawable/ic_insert_photo_black_24dp"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="好友"
            android:icon="@drawable/ic_play_circle_outline_black_24dp"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="附近"
            android:icon="@drawable/ic_clear_all_black_24dp"
            />
    </android.support.design.widget.TabLayout>

</LinearLayout>複製程式碼

當然了也可在程式碼中動態新增Tab,前面已經說過了,不再重複,效果:

Material Design 之 TabLayout 使用
scrollable_tabs.gif

Tabs 居中顯示
 <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="center"
        app:tabIndicatorColor="@android:color/holo_red_light"
        app:tabIndicatorHeight="2dp"
        app:tabSelectedTextColor="@android:color/holo_red_light"

        >
         <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="個性推薦"
        />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="歌單"
            />
        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="主播電臺"
            />

    </android.support.design.widget.TabLayout>複製程式碼

效果圖如下:

Material Design 之 TabLayout 使用
center_tabs.png

TabLayout + ViewPager + Fragment

這種組合可能是我們專案裡面用的最多的,接下來看一下怎麼使用

1,佈局檔案,TabLayout 下面有一個ViewPager

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
 <android.support.v7.widget.Toolbar
     android:layout_width="match_parent"
     android:layout_height="?attr/actionBarSize"
     android:background="@color/colorPrimary"
     app:titleTextColor="@color/white"
     app:title="TabLayout示例"
     app:navigationIcon="@drawable/ic_book_list"
     >

 </android.support.v7.widget.Toolbar>

 <android.support.design.widget.TabLayout
     android:id="@+id/tabLayout"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@color/colorPrimary"
     app:tabTextColor="@color/white"
     app:tabSelectedTextColor="@color/white"
     app:tabIndicatorColor="@android:color/holo_green_light"
     app:tabIndicatorHeight="2dp"
     app:tabGravity="fill"
     app:tabMode="fixed"
     >

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

 <android.support.v4.view.ViewPager
     android:id="@+id/view_pager"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

 </android.support.v4.view.ViewPager>
</LinearLayout>複製程式碼

2,Activity 程式碼,View 的Adapter 和Tab對應的Fragment 程式碼相對簡單,沒有貼出來,需要的請看Demo,程式碼如下:

/**
 * Created by zhouwei on 16/12/23.
 */

public class TabActivity extends AppCompatActivity {
    public static final String TAG = "TabActivity";
    public static final String []sTitle = new String[]{"ITEM FIRST","ITEM SECOND","ITEM THIRD"};
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_layout_ac);
        initView();
    }

    private void initView() {
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[0]));
        mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[1]));
        mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[2]));
      //  mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[3]));
      //  mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[4]));
      //  mTabLayout.addTab(mTabLayout.newTab().setText(sTitle[5]));

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.i(TAG,"onTabSelected:"+tab.getText());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mTabLayout.setupWithViewPager(mViewPager);
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(FirstFragment.newInstance());
        fragments.add(SecondFragment.newInstance());
        fragments.add(ThirdFragment.newInstance());

        MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),fragments, Arrays.asList(sTitle));
        mViewPager.setAdapter(adapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
               Log.i(TAG,"select page:"+position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }
}複製程式碼

3,其中重要的一步是TabLayout 和ViewPager 關聯起來,TabLayout有一個setupWithViewPager方法,

 mTabLayout.setupWithViewPager(mViewPager);複製程式碼

4,效果圖:

Material Design 之 TabLayout 使用
TabLayout_ViewPager_Fragment.gif

另一種方式關聯ViewPager

上面是通過setupWithViewPager 來關聯TabLayout和ViewPager的,還有另外一種方式,將TabLayout,作為ViewPager的子View。

<android.support.v4.view.ViewPager
     android:id="@+id/view_pager"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
  <android.support.design.widget.TabLayout
      android:id="@+id/tabLayout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:background="@color/colorPrimary"
      app:tabTextColor="@color/white"
      app:tabSelectedTextColor="@color/white"
      app:tabIndicatorColor="@android:color/holo_green_light"
      app:tabIndicatorHeight="2dp"
      app:tabGravity="fill"
      app:tabMode="fixed"
      >

  </android.support.design.widget.TabLayout>
 </android.support.v4.view.ViewPager>複製程式碼

然後在程式碼中我們就不需要去手動關聯了,不需要寫下面這行程式碼了

 mTabLayout.setupWithViewPager(mViewPager);複製程式碼

效果和上面完全是一樣的。其實也很簡單,這種方式無非就是TabLayout 獲取了Parent ,然後判斷是不是ViewPager,如果是ViewPager,它就幫我們呼叫了setupWithViewPager () 方法。原始碼中我們可以看到,在onAttachedToWindow 方法被回撥的時候,獲取Parent 判斷的,程式碼如下:

 @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (mViewPager == null) {
            // If we don't have a ViewPager already, check if our parent is a ViewPager to
            // setup with it automatically
            final ViewParent vp = getParent();
            if (vp instanceof ViewPager) {
                // If we have a ViewPager parent and we've been added as part of its decor, let's
                // assume that we should automatically setup to display any titles
                setupWithViewPager((ViewPager) vp, true, true);
            }
        }
    }複製程式碼

最後

以上就是TabLayout 使用的全部內容,由於Tabs的互動很有好,所以 在app 裡運用得比較多,掌握了TabLayout ,我們開發起來就得心應手了,另外,TabLayout 和AppbarLayout 結合能做出許多很酷的效果,還不會用AppbarLayout 的可以去看一下我前面的部落格。如果有什麼問題,歡迎討論。

最後Demo 請戳MaterialDesignSamples

參考:
Material Design Component -Tabs

相關文章