Material Design 之 TabLayout 使用

写在前面

更多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属性,代码如下:
```java
 <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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,087评论 2 44
  • “刘叔!你……”这个信息无异于晴天霹雳,震惊的我一下子跳了起来。 “稍安勿燥,”刘叔用手指指仍然留在我盘子里的那片...
    默陌朋阅读 443评论 0 1
  • 你送我的一万个祝福 不及他的一个拥抱 说好的情深意后 转眼是缘浅衣薄 我没有锁的铜臂 无法将你的一生套牢 可我有一...
    飞狐119阅读 206评论 3 3