Material Design 之 TabLayout 使用

7,285 阅读8分钟

写在前面

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