MaterialDesign学习篇(四),如何使用TabLayout

什么是TabLayout

上图中,我们可以看到,该页面分成三个页签,每个页签对应不同的内容,如果让我们来实现布局的话,我们会很容易地想到布局为一个页签指示器+ViewPager,以前,相信各位大多使用的是GitHub上的开源框架PagerSlidingTabTrip来实现指示器的效果,而如今,Android中也有自带这种指示器的控件TabLayout,TabLayout存在于android design库中,它提供了一个水平的布局来展示Tabs。

一 如何使用TabLayout

1.要使用TabLayout,首先要添加 android support design包的依赖,在app模块的build.gradle中添加:

dependencies {
    ...
    compile 'com.android.support:design:26.0.0-alpha1'
}

2.在布局文件的xml中,使用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"
    >

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        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="页签1"
            />

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="页签2"
            />

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="页签3"
            />
        
    </android.support.design.widget.TabLayout>

</LinearLayout>

代码中我们可以看到,<TabLayout></TabLayout>之间包裹着TabItem,也就是每个页签的配置,我们这里只是简单地配置了文字,先运行下看看效果:

3.如何设置页签的点击事件

在java文件中,我们根据id找到TabLayout,为其添加页签选中的监听,当选中标签的时候,弹出对应标签的文字:

TabLayout tabLayout = (TabLayout) findViewById(R.id.tab);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Toast.makeText(TabLayoutActivity.this, tab.getText(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

效果如图:

动态创建Tab

上面我们简单演示了在布局文件中配置了TabLayout和对应的页签TabItem,接下来我们演示如何动态创建页签,修改布局文件:

<?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"
    >

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

在Activity中找到TabLayout,并为其动态添加Tab:

public class TabLayoutActivity extends AppCompatActivity {

    private String[] titles = new String[]{
            "体育",
            "社会",
            "新闻"
    };

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

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab);
        for (int i = 0; i < titles.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();//创建tab
            tab.setText(titles[i]);//设置文字
            tabLayout.addTab(tab);//添加到tabLayout中
        }

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Toast.makeText(TabLayoutActivity.this, tab.getText(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

效果如图:

为Tab设置图标

Tab的创建是通过调用TabLayout的newTab()方法,创建出来的Tab对象即页签对象,除了setText()方法设置文字外,还可以设置对应的图标,通过调用setIcon()方法,就可以设置Tab的图标:

  for (int i = 0; i < titles.length; i++) {
        TabLayout.Tab tab = tabLayout.newTab();//创建tab
        tab.setText(titles[i]);//设置文字
        tab.setIcon(R.mipmap.ic_launcher);//设置图标
        tabLayout.addTab(tab);//添加到tabLayout中
    }

效果如图:

设置更加美观的Tab

如果不喜欢图标在页签的上面,有别的需求,比如图标在页签的左边,那么这时,可以使用Tab的setCustomView(View view)方法,可以通过布局填充器将自己布局好的xml填充成View对象,然后设置进去,就可以实现更加美观的页签了,有兴趣的同学可以试试看。

修改TabLayout的样式

Tablayout支持定制化修改,提供了不少自定义属性供开发者进行设置。有以下属性支持修改:

tabBackground=""                            tablayout的背景颜色

tabIndicatorColor=""                         指示器的颜色

tabIndicatorHeight=""                        指示器的高度

tabGravity=""                                指示器的位置

tabMode=""                                   显示模式

tabSelectedTextColor=""                      选中时文字颜色

tabTextColor=""                              未选中时文字颜色

tabTextAppearance=""                         字体外观

tabMaxWidth=""                               tab最大宽度

tabMinWidth=""                               tab最小宽度

tabPadding=""                                tab内边距

自定义TabLayout:

下面我们简单修改下TabLayout提供修改的属性,看看修改后是怎样的效果,修改布局文件:

<android.support.design.widget.TabLayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@color/colorPrimary"
    app:tabIndicatorColor="@android:color/darker_gray"
    app:tabIndicatorHeight="5dp"
    app:tabSelectedTextColor="@android:color/holo_blue_light"
    app:tabTextColor="@android:color/white"
    app:tabTextAppearance="@style/TabTextStyle"
    />

这里我们为TabLayout设置了蓝色的背景色,设置了指示器的高度和颜色(灰色),设置了选中时文字的颜色为浅蓝色,未选中时为白色,还设置了字体的外观,字体的外观设置需要在style.xml中定义样式,如下:

<style name="TabTextStyle" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">16sp</item>
</style>

这里定义了字体的大小,样式中还可以设置字体其他外观,比如设置字体是否加粗等。

看一下自定义的TabLayout效果:

可以看到,效果和我们设置的一样。

Tab的位置和显示模式(tabGravity和tabMode)

1.tabGravity有两个值可选,分别是center(居中)和fill(填满),默认tabGravity="fill",填满,我们将它设置为center,看下效果:

 <android.support.design.widget.TabLayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@color/colorPrimary"
    app:tabIndicatorColor="@android:color/darker_gray"
    app:tabIndicatorHeight="5dp"
    app:tabSelectedTextColor="@android:color/holo_blue_light"
    app:tabTextColor="@android:color/white"
    app:tabTextAppearance="@style/TabTextStyle"
    app:tabGravity="center"
    />

可以看到TabLayout的宽度没有填满,而且整个TabLayout居中显示。

2.当有很多个tab,多到屏幕放不下的时候,比如今日头条的TabLayout,我们需要将TabLayout的显示模式tabMode更改为scrollable,这样整个TabLayout就可以左右滑动,TabLayout默认tabMode为fixed(固定),我们将其修改为scrollable:

<android.support.design.widget.TabLayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@color/colorPrimary"
    app:tabIndicatorColor="@android:color/darker_gray"
    app:tabIndicatorHeight="5dp"
    app:tabSelectedTextColor="@android:color/holo_blue_light"
    app:tabTextColor="@android:color/white"
    app:tabTextAppearance="@style/TabTextStyle"
    app:tabGravity="center"
    app:tabMode="scrollable"
    />

添加多一些页签:

    String[] channels = getResources().getStringArray(R.array.channel);
    for (int i = 0; i < channels.length; i++) {
        TabLayout.Tab tab = tabLayout.newTab();//创建tab
        tab.setText(channels[i]);//设置文字
        tabLayout.addTab(tab);//添加到tabLayout中
    }

channel是一个定义在xml中的string-array:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="channel">
        <item>推荐</item>
        <item>视频</item>
        <item>热点</item>
        <item>社会</item>
        <item>娱乐</item>
        <item>科技</item>
        <item>汽车</item>
        <item>体育</item>
        <item>财经</item>
        <item>军事</item>
        <item>国际</item>
        <item>时尚</item>
        <item>游戏</item>
        <item>旅游</item>
        <item>历史</item>
        <item>探索</item>
        <item>美食</item>
        <item>育儿</item>
        <item>养生</item>
        <item>故事</item>
        <item>美文</item>
    </string-array>
</resources>

运行的效果如下:

可以看到TabLayout有许多Tab,且可以左右滑动。需要注意的是,当设置tabMode为scrollable时,此时设置tabGravity已经无效,无论设置为哪个值,它都是填满的效果。

TabLayout结合ViewPager

TabLayout + ViewPager 在开发中经常使用到,即上面显示页签,下面展示不同的fragment,就如今日头条,现在我们仿造今日头条的首页,演示下如果使用TabLayout + ViewPager。

首先,在布局文件中配置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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabBackground="@color/colorPrimary"
        app:tabIndicatorColor="@android:color/darker_gray"
        app:tabIndicatorHeight="5dp"
        app:tabSelectedTextColor="@android:color/holo_blue_light"
        app:tabTextColor="@android:color/white"
        app:tabTextAppearance="@style/TabTextStyle"
        app:tabGravity="center"
        app:tabMode="scrollable"
        />

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

</LinearLayout>

java文件中,设置TabLayout和ViewPager关联起来:

public class TabLayoutActivity extends AppCompatActivity {

    private TabLayout mTabLayout;
    private ViewPager mVpContent;

    private List<ContentFragment> mFragments = new ArrayList<>();
    private String[] mTitles;

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

        initView();
        initData();
        initListener();
    }

    private void initView() {
        mTabLayout = (TabLayout) findViewById(R.id.tab);
        mVpContent = (ViewPager) findViewById(R.id.vp_content);
    }

    private void initData() {
        mTitles = getResources().getStringArray(R.array.channel);
        for (int i = 0; i < mTitles.length; i++) {
            ContentFragment fragment = new ContentFragment();
            Bundle bundle = new Bundle();
            bundle.putString(ContentFragment.TEXT, mTitles[i]);
            fragment.setArguments(bundle);
            mFragments.add(fragment);//添加到fragment中
        }
    }

    private void initListener() {
        TabAdapter tabAdapter = new TabAdapter(getSupportFragmentManager(), mFragments, mTitles);
        mVpContent.setAdapter(tabAdapter);//为viewPager设置adapter
        mTabLayout.setupWithViewPager(mVpContent);//将TabLayout和ViewPager关联
    }
}

运行的效果如下:

可以看到,TabLayout和ViewPager已经关联起来,当点击页签的时候,ViewPager会切换到对应的fragment,滑动ViewPager,对应页签也会跟着改变。

这里需要注意的是,实现ViewPager的adapter时,需要重写Adapter的getPageTitle()方法,返回对应页签的内容,这样TabLayout才会有对应的页签。

好了,到这里关于TabLayout的介绍就到此为止了,想看源码的话,可以点击以下链接:

https://github.com/chaychan/MaterialDesignExercise

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

推荐阅读更多精彩内容