Android TabLayout 分分鐘打造一個滑動標(biāo)簽頁

使用滾動的標(biāo)簽指示器和滑動的內(nèi)容頁面张峰,是手機(jī)應(yīng)用經(jīng)常出現(xiàn)的一種設(shè)計風(fēng)格,常見的比較出名的應(yīng)用有:微信(首頁)堪簿、網(wǎng)易新聞痊乾、今日頭條和知乎等。有過幾年安卓開發(fā)經(jīng)驗(yàn)的朋友肯定知道椭更,在GitHub上符喝,實(shí)現(xiàn)這種功能有兩個比較出名的開源項(xiàng)目:PagerSlidingTabStrip 和 JakeWharton大神的ViewPagerIndicator,特別是后者甜孤,估計大家或多或少都曾今在自己的項(xiàng)目中使用到過协饲。當(dāng)然,現(xiàn)在也能使用這兩個開源庫缴川,只是我們有了更多的選擇茉稠,比如本文給大家介紹的TabLayout

自2014年I/O結(jié)束后把夸,Google在Support Design包中發(fā)布了一些列新的控件而线,其中就包括TabLayout。配合著ViewPager和Fragment的使用恋日,TabLayout可以幫助開發(fā)者們分分鐘打造一個滑動標(biāo)簽頁膀篮,非常方便。本文作為Material Design系列學(xué)習(xí)的第一篇岂膳,將介紹TabLayout的兩種常見使用場景:頂部標(biāo)簽頁(如知乎)誓竿,底部菜單欄(如微信)。先看一下最終能夠?qū)崿F(xiàn)的效果:

頂部標(biāo)簽.gif
底部菜單.gif

基礎(chǔ)介紹


我們可以在代碼中定義TabLayout的每一個Tab項(xiàng)谈截,也可以通過TabLayout對象調(diào)用newTab()方法創(chuàng)建筷屡,比如:

 TabLayout tabLayout = ...; 
tabLayout.addTab(tabLayout.newTab().setText("Tab 1")); 
tabLayout.addTab(tabLayout.newTab().setText("Tab 2")); 
tabLayout.addTab(tabLayout.newTab().setText("Tab 3")); 

TabLayout的寬度分配模式、Indicator下劃線的高度簸喂、字體顏色毙死、選擇監(jiān)聽事件等這些方法都可以在官網(wǎng)看到,本文主要講TabLayout的常見應(yīng)用場景喻鳄,所以各屬性的設(shè)置就不碎碎念了扼倘,大家可以自行查閱。

頂部標(biāo)簽頁


TabLayout的使用需要借助Android Design包除呵,所以我們需要在 build.gradle中引入design包:

compile 'com.android.support:design:23.3.0'

在布局文件 activity_tab_layout.xml 中加入TabLayout和ViewPager控件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        layout="@layout/include_toolbar"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tl_tab"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_48"
        android:background="@color/blue">

    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>

</LinearLayout>

然后我們看一下 TabLayoutActivity 中的代碼:

package com.yifeng.mdstudysamples;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yifeng on 16/8/3.
 *
 */
public class TabLayoutActivity extends BaseActivity {

    private TabLayout mTabTl;
    private ViewPager mContentVp;

    private List<String> tabIndicators;
    private List<Fragment> tabFragments;
    private ContentPagerAdapter contentAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout);

        mTabTl = (TabLayout) findViewById(R.id.tl_tab);
        mContentVp = (ViewPager) findViewById(R.id.vp_content);

        initContent();
        initTab();
    }

    private void initTab(){
        mTabTl.setTabMode(TabLayout.MODE_SCROLLABLE);
        mTabTl.setTabTextColors(ContextCompat.getColor(this, R.color.gray), ContextCompat.getColor(this, R.color.white));
        mTabTl.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.white));
        ViewCompat.setElevation(mTabTl, 10);
        mTabTl.setupWithViewPager(mContentVp);
    }

    private void initContent(){
        tabIndicators = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            tabIndicators.add("Tab " + i);
        }
        tabFragments = new ArrayList<>();
        for (String s : tabIndicators) {
            tabFragments.add(TabContentFragment.newInstance(s));
        }
        contentAdapter = new ContentPagerAdapter(getSupportFragmentManager());
        mContentVp.setAdapter(contentAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_tab_layout, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.tab_add:
                tabIndicators.add("Tab " + tabIndicators.size());
                tabFragments.add(TabContentFragment.newInstance(tabIndicators.get(tabIndicators.size()-1)));
                contentAdapter.notifyDataSetChanged();
                return true;

            case R.id.tab_mode_fixed:
                mTabTl.setTabMode(TabLayout.MODE_FIXED);
                return true;

            case R.id.tab_mode_scrollable:
                mTabTl.setTabMode(TabLayout.MODE_SCROLLABLE);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    class ContentPagerAdapter extends FragmentPagerAdapter{

        public ContentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return tabFragments.get(position);
        }

        @Override
        public int getCount() {
            return tabIndicators.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabIndicators.get(position);
        }
    }

}

核心代碼有兩個地方再菊,第一個是 setupWithViewPager 方法將TabLayout和ViewPager綁定在一起隅肥,使雙方各自的改變都能直接影響另一方,解放了開發(fā)人員對雙方變動事件的監(jiān)聽袄简;第二個是在ViewPager的Adapter適配器中重寫 getPageTitle 方法,在這個方法中設(shè)置標(biāo)簽指示器的標(biāo)題泛啸。

底部菜單欄


上面我們使用了系統(tǒng)定義好的View做了一個純文字加下劃線組合的標(biāo)簽指示器绿语。其實(shí),我們也能自定義一個布局候址,然后賦值給TabLayout的Tab視圖吕粹,比如做一個微信首頁界面。

相比頂部標(biāo)簽指示器岗仑,底部菜單欄只是將TabLayout布局在了下面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        layout="@layout/include_toolbar"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

    </android.support.v4.view.ViewPager>

    <android.support.design.widget.TabLayout
        android:id="@+id/tl_tab"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_56"
        android:background="@color/white">

    </android.support.design.widget.TabLayout>

</LinearLayout>

在Activity代碼中匹耕,設(shè)置TabLayout的指示器高度為0,即達(dá)到了隱藏Indicator的目的荠雕,然后通過getTabAt(position)的方法獲取TabLayout的每一個Tab稳其,并賦值為自定義布局視圖,代碼也很簡單:

package com.yifeng.mdstudysamples;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yifeng on 16/8/3.
 *
 */
public class TabLayoutBottomActivity extends BaseActivity {

    private TabLayout mTabTl;
    private ViewPager mContentVp;

    private List<String> tabIndicators;
    private List<Fragment> tabFragments;
    private ContentPagerAdapter contentAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout_bottom);

        mTabTl = (TabLayout) findViewById(R.id.tl_tab);
        mContentVp = (ViewPager) findViewById(R.id.vp_content);

        initContent();
        initTab();
    }

    private void initTab(){
        mTabTl.setTabMode(TabLayout.MODE_FIXED);
        mTabTl.setSelectedTabIndicatorHeight(0);
        ViewCompat.setElevation(mTabTl, 10);
        mTabTl.setupWithViewPager(mContentVp);
        for (int i = 0; i < tabIndicators.size(); i++) {
            TabLayout.Tab itemTab = mTabTl.getTabAt(i);
            if (itemTab!=null){
                itemTab.setCustomView(R.layout.item_tab_layout_custom);
                TextView itemTv = (TextView) itemTab.getCustomView().findViewById(R.id.tv_menu_item);
                itemTv.setText(tabIndicators.get(i));
            }
        }
        mTabTl.getTabAt(0).getCustomView().setSelected(true);
    }

    private void initContent(){
        tabIndicators = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            tabIndicators.add("Tab " + i);
        }
        tabFragments = new ArrayList<>();
        for (String s : tabIndicators) {
            tabFragments.add(TabContentFragment.newInstance(s));
        }
        contentAdapter = new ContentPagerAdapter(getSupportFragmentManager());
        mContentVp.setAdapter(contentAdapter);
    }

    class ContentPagerAdapter extends FragmentPagerAdapter{

        public ContentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return tabFragments.get(position);
        }

        @Override
        public int getCount() {
            return tabIndicators.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabIndicators.get(position);
        }
    }

}

從這兩種使用場景可以看出炸卑,利用TabLayout做一個滑動標(biāo)簽頁或者底部菜單欄既鞠,實(shí)現(xiàn)起來非常方便,代碼量也不多盖文,極大地減少了我們的開發(fā)量嘱蛋。但是,TabLayout也不是萬能的五续,如果想做出更多地特效還是需要我們自己去開發(fā)洒敏。所以,如果你想自己做一個滑動標(biāo)簽指示器疙驾,強(qiáng)烈推薦大家去看看TabLayout的源碼凶伙,相信對你一定有所啟發(fā)。

示例源碼


我在GitHub上建立了一個Repository它碎,用來存放整個Android Material Design系列控件的學(xué)習(xí)案例镊靴,會伴隨著文章逐漸更新完善,歡迎大家補(bǔ)充交流链韭,Star地址:

https://github.com/Mike-bel/MDStudySamples

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末偏竟,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子敞峭,更是在濱河造成了極大的恐慌踊谋,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件旋讹,死亡現(xiàn)場離奇詭異殖蚕,居然都是意外死亡轿衔,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進(jìn)店門睦疫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來害驹,“玉大人,你說我怎么就攤上這事蛤育⊥鸸伲” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵瓦糕,是天一觀的道長底洗。 經(jīng)常有香客問我,道長咕娄,這世上最難降的妖魔是什么亥揖? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮圣勒,結(jié)果婚禮上费变,老公的妹妹穿的比我還像新娘。我一直安慰自己圣贸,他們只是感情好胡控,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著旁趟,像睡著了一般昼激。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上锡搜,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天橙困,我揣著相機(jī)與錄音,去河邊找鬼耕餐。 笑死凡傅,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的肠缔。 我是一名探鬼主播夏跷,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼明未!你這毒婦竟也來了槽华?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤趟妥,失蹤者是張志新(化名)和其女友劉穎猫态,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡亲雪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年勇凭,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片义辕。...
    茶點(diǎn)故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡虾标,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出灌砖,到底是詐尸還是另有隱情璧函,我是刑警寧澤,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布周崭,位于F島的核電站,受9級特大地震影響喳张,放射性物質(zhì)發(fā)生泄漏续镇。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一销部、第九天 我趴在偏房一處隱蔽的房頂上張望摸航。 院中可真熱鬧,春花似錦舅桩、人聲如沸酱虎。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽读串。三九已至,卻和暖如春撒妈,著一層夾襖步出監(jiān)牢的瞬間恢暖,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工狰右, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留杰捂,地道東北人。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓棋蚌,卻偏偏與公主長得像嫁佳,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子谷暮,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容