Material Design 之 TabLayout 使用

寫在前面

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

這是Material Design系列文章的第四篇,講一下項目中用得很是多的一個組件-Tabs,在一個app中,Tabs 使不一樣視圖和功能之間的切換變得簡單。使用 tabs 將大量關聯的數據或者選項劃分紅更易理解的分組,能夠在不須要切換出當先上下文的狀況下,有效的進行內容導航和內容組織,便於用戶操做。提高用戶體驗。下面一塊兒來看一下Tabs的使用。java

Tabs 的使用方式

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

(1) 默認的app bar + 固定的tab bargit

tabs1.png

(2)可擴展的app bar+ tab bargithub

tabs2.png

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

tabs3.png

(4)默認的app bar + 可滾動的app bar

tabs4.png

(5)和指示器同樣字體顏色的tabs ide

tabs5.png

(6)默認app bar +固定的帶圖標的 app bar

tabs6.png

(7) icon 顏色和指示器顏色同樣的tabs 佈局

tabs7.png

以上就是Material Design 官方給出的Tabs 的一些使用模式。基本上能涵蓋咱們項目中的使用。post

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("排行榜"));複製代碼

效果圖以下:

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));複製代碼

效果以下:

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,前面已經說過了,再也不重複,效果:

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>複製代碼

效果圖以下:

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,效果圖:

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

相關文章
相關標籤/搜索