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