Material Design 之 TabLayout 使用

pzx87r98 7年前發布 | 21K 次閱讀 Android開發 移動開發 Material Design

寫在前面

更多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

tabs1.png

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

tabs2.png

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

tabs3.png

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

tabs4.png

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

tabs5.png

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

tabs6.png

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

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="

</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></code></pre>

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("排行榜"));</code></pre> 

效果圖如下:

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 的可以去看一下我前面的博客。如果有什么問題,歡迎討論。

 

參考:

Material Design Component -Tabs

 

來自:http://www.jianshu.com/p/13f334eb16ce

 

 本文由用戶 pzx87r98 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!