Material Design 之 TabLayout 使用

pzx87r98 7年前
   <h3>写在前面</h3>    <p>更多Material Design 文章请看:</p>    <p><a href="http://www.open-open.com/lib/view/open1483064665647.html">Material Design 之 Toolbar 开发实践总结</a></p>    <p><a href="/misc/goto?guid=4959732247070599132" rel="nofollow,noindex">Material Design之 AppbarLayout 开发实践总结</a></p>    <p><a href="http://www.open-open.com/lib/view/open1483065139668.html">Material Design 之 Behavior的使用和自定义Behavior</a></p>    <p>这是Material Design系列文章的第四篇,讲一下项目中用得非常多的一个组件-Tabs,在一个app中,Tabs 使不同视图和功能之间的切换变得简单。使用 tabs 将大量关联的数据或者选项划分成更易理解的分组,可以在不需要切换出当先上下文的情况下,有效的进行内容导航和内容组织,</p>    <p>便于用户操作。提升用户体验。下面一起来看一下Tabs的使用。</p>    <h3>Tabs 的使用方式</h3>    <p>用法:tab 用来显示有关联的分组内容。tab标签用来简要的描述该Tab下的内容。</p>    <p>(1) 默认的app bar + 固定的tab bar</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/f11450bbc203629e9ba517b1086efa1d.png"></p>    <p style="text-align:center">tabs1.png</p>    <p>(2)可扩展的app bar+ tab bar</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/4f9fedaafce4a6a58395eeb9c9b9b4ce.png"></p>    <p style="text-align:center">tabs2.png</p>    <p>(3)随着滚动内容被锁定在顶部的ab bar</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/9cd666171519d36365f3e8fd4630e811.png"></p>    <p style="text-align:center">tabs3.png</p>    <p>(4)默认的app bar + 可滚动的app bar</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/5e3ce14947a1df04c3195d6a069b5073.png"></p>    <p style="text-align:center">tabs4.png</p>    <p>(5)和指示器一样字体颜色的tabs</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/e915342e5520440b54b6c68fafb4aed6.png"></p>    <p style="text-align:center">tabs5.png</p>    <p>(6)默认app bar +固定的带图标的 app bar</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/e3bc9a5de643fb676d108a00344f2002.png"></p>    <p style="text-align:center">tabs6.png</p>    <p>(7) icon 颜色和指示器颜色一样的tabs</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/3e8eccd8d4a0e34719c1601ab25f012f.png"></p>    <p style="text-align:center">tabs7.png</p>    <p>以上就是Material Design 官方给出的Tabs 的一些使用模式。基本上能涵盖我们项目中的使用。</p>    <p>Tab特性:</p>    <ul>     <li>Tabs 应该在一行内,如果有必要,标签可以显示两行然后截断</li>     <li>Tabs 不应该被嵌套,也就是说一个Tab的内容里不应该包含另一组Tabs</li>     <li>Tabs 控制的显示内容的定位要一致。</li>     <li>Tab 中当前可见内容要高亮显示。</li>     <li>Tabs 应该归类并且每组 tabs 中内容顺序相连。</li>     <li>一组 tabs 至少包含 2 个 tab 并且不多于 6 个 tab。</li>    </ul>    <p>其他的一些使用细节和规范请查看 Material Design 的官方文档。</p>    <h3>Tabs 的具体实现-TabLayout</h3>    <p>上面讲了Tabs的一些特性、规范和使用模式,下面我们看一下具体在代码中的 实现。要实现一组Tabs,Google 给我提供了一个控件-TabLayout。来看一下TabLayout的介绍和使用。</p>    <p>TabLayout 提供一个水平方向的布局来显示Tabs,继承的是 HorizontalScrollView 这个类。</p>    <p>TabLayout 基础</p>    <p>1,创建Tabs (代码中)</p>    <p>Tabs的显示是通过 TabLayout.Tab 来完成的,我们可以通过newTab() 来创建,在这儿你也可以改变Tab的标签(label)和icon 通过 setText(int) 和setIcon(int)。最后需要通addTab(Tab ) 方法把Tab添加到TabLayout 显示。代码如下:</p>    <pre>  <code class="language-java"><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></code></pre>    <p>Activity 中添加Tab:</p>    <pre>  <code class="language-java">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>    <p>效果图如下:</p>    <p><img src="https://simg.open-open.com/show/37365462ab5b727d0cbdca30ea072de9.png"></p>    <p style="text-align:center">simple_tabLayout.png</p>    <p>2,创建Tabs (xml 布局文件中)</p>    <p>直接在xml 添加Tab:</p>    <p>上面是在代码中通过addTab 添加Tab,也可以直接在 xml 中添加 ,使用TabItem,代码如下:</p>    <pre>  <code class="language-java"><?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></code></pre>    <p>效果第一种方式是一样的,就不再多讲。</p>    <p>3,带Icon的Tabs</p>    <p>创建Tab的时候是可以设置图标的,可以在布局文件中用TabItem的icon属性,代码如下:</p>    <pre>  <code class="language-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"               /></code></pre>    <p>也可依在代码中设置:</p>    <pre>  <code class="language-java">mTabLayout.addTab(mTabLayout.newTab().setText("个性推荐").setIcon(R.drawable.ic_favorite_border_black_24dp));</code></pre>    <p>效果如下:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/f5996c65586976fe90f8e8d9acc6416e.png"></p>    <p>tab_with_icon.png</p>    <p>当然了,还可是只有Icon 的Tab,把设置的标签去掉不让显示就好了,这里就不多讲了。</p>    <p>4,Tab 选中监听</p>    <p>Tab切换的时候,我们需要切换页面的内容,这时候就需要为它设置一个监听器TabLayout.OnTabSelectedListener,如下:</p>    <pre>  <code class="language-java">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) {                }          });</code></pre>    <p>然后就可以在onTabSelected 做对应的逻辑处理了,切换到哪个Tab就显示对应Tab 的内容。</p>    <p>TabLayout 进阶</p>    <p>上面讲到了TabLayout 最简单的使用,实际项目中,我们的需求更复杂一些,比如:需要改变Tabs 的指示器的高和颜色,需要改变Tab的宽高,Tab的颜色,固定的Tabs,可滚动的Tabs ,Tabs+viewPager+Fragment 的使用等等。因此我们需要了解TabLayout的一些重要属性。</p>    <ul>     <li> <p>app:tabBackground 设置Tabs的背景</p> </li>     <li> <p>app:tabGravity 为Tabs设置Gravity,有两个常量值,GRAVITY_CENTER,GRAVITY_FILL,用法:</p> <pre>  <code class="language-java">app:tabGravity="center"</code></pre> <p>或者</p> <pre>  <code class="language-java">app:tabGravity="fill"</code></pre> <p>值为center,Tabs就居中显示,fill 就充满TabLayout 。</p> </li>    </ul>    <ul>     <li> <p>app:tabIndicatorColor 设置指示器的颜色(默认情况下指示器的颜色为colorAccent)</p> </li>     <li> <p>app:tabIndicatorHeight 设置指示器的高度,Material Design 规范建议是2dp</p> </li>     <li> <p>app:tabMaxWidth 设置 Tab 的最大宽度</p> </li>     <li> <p>app:tabMinWidth 设置 Tab 的最小宽度</p> </li>     <li> <p>app:tabMode 设置Tabs的显示模式,有两个常量值,MODE_FIXED,MODE_SCROLLABLE。用法:</p> <pre>  <code class="language-java">app:tabMode="fixed"</code></pre> <p>或者</p> <pre>  <code class="language-java">app:tabMode="scrollable"</code></pre> <p>fixed 表示固定的Tab,scrollable 可滚动的Tab, Tab个数少的时候用 fixed,当Tab个数较多(大于四个或者5个)时用scrollable。</p> </li>     <li> <p>app:tabPadding 这几个很简单设置Tab padding</p> </li>     <li>app:tabPaddingTop</li>     <li>app:tabPaddingBottom</li>     <li>app:tabPaddingStart</li>     <li> <p>app:tabPaddingEnd</p> </li>     <li> <p>app:tabSelectedTextColor 设置Tab选中后,文字显示的颜色</p> </li>     <li> <p>app:tabTextColor 设置Tab未选中,文字显示的颜色</p> </li>    </ul>    <p>以上就是TabLayout 的常用属性,了解了这些属性后我们就能做出更多的效果了。</p>    <p>可滚动的Tabs:</p>    <pre>  <code class="language-java"><?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></code></pre>    <p>当然了也可在代码中动态添加Tab,前面已经说过了,不再重复,效果:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/8bb486c343dd35760f3e1f73804ca0e8.gif"></p>    <p style="text-align:center">scrollable_tabs.gif</p>    <p>Tabs 居中显示</p>    <pre>  <code class="language-java"><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></code></pre>    <p>效果图如下:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/0dabb1497e64cdc79de08ff9630ab59e.png"></p>    <p style="text-align:center">center_tabs.png</p>    <p>TabLayout + ViewPager + Fragment</p>    <p>这种组合可能是我们项目里面用的最多的,接下来看一下怎么使用</p>    <p>1,布局文件,TabLayout 下面有一个ViewPager</p>    <pre>  <code class="language-java"><?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></code></pre>    <p>2,Activity 代码,View 的Adapter 和Tab对应的Fragment 代码相对简单,没有贴出来,需要的请看Demo,代码如下:</p>    <pre>  <code class="language-java">/**   * 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) {                }          });        }  }</code></pre>    <p>3,其中重要的一步是TabLayout 和ViewPager 关联起来,TabLayout有一个setupWithViewPager方法,</p>    <pre>  <code class="language-java">mTabLayout.setupWithViewPager(mViewPager);</code></pre>    <p>4,效果图:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/1efee6a9a667c275ba8062a661e1c58f.gif"></p>    <p style="text-align:center">TabLayout_ViewPager_Fragment.gif</p>    <p>另一种方式关联ViewPager</p>    <p>上面是通过setupWithViewPager 来关联TabLayout和ViewPager的,还有另外一种方式,将TabLayout,作为ViewPager的子View。</p>    <pre>  <code class="language-java"><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></code></pre>    <p>然后在代码中我们就不需要去手动关联了,不需要写下面这行代码了</p>    <pre>  <code class="language-java">mTabLayout.setupWithViewPager(mViewPager);</code></pre>    <p>效果和上面完全是一样的。其实也很简单,这种方式无非就是TabLayout 获取了Parent ,然后判断是不是ViewPager,如果是ViewPager,它就帮我们调用了setupWithViewPager () 方法。源码中我们可以看到,在onAttachedToWindow 方法被回调的时候,获取Parent 判断的,代码如下:</p>    <pre>  <code class="language-java">@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);              }          }      }</code></pre>    <h3>最后</h3>    <p>以上就是TabLayout 使用的全部内容,由于Tabs的交互很有好,所以 在app 里运用得比较多,掌握了TabLayout ,我们开发起来就得心应手了,另外,TabLayout 和AppbarLayout 结合能做出许多很酷的效果,还不会用AppbarLayout 的可以去看一下我前面的博客。如果有什么问题,欢迎讨论。</p>    <p> </p>    <p>参考:</p>    <p><a href="/misc/goto?guid=4959732247175025521" rel="nofollow,noindex">Material Design Component -Tabs</a></p>    <p> </p>    <p>来自:http://www.jianshu.com/p/13f334eb16ce</p>    <p> </p>