为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Android

什么是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

点击查看更多内容
5人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
61
获赞与收藏
486

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消