谷歌TabLayout及FlycoTabLayout三方库入门

一、简介

谷歌在 2014 年 I/O 大会上重磅推出了一套全新的界面设计语言 Material Design ,用于解决 Android 平台界面风格不统一的问题,并且亲力亲为从 Android 5.0 系统开始将自家所有内置应用统一使用 Material Design 风格进行设计。

但由于缺少相关 API 支持,作为开发者实现起来难度较大。于是,谷歌在 2015 年 I/O 大会上又推出了 Design Support 库,将最具代表性的控件和效果进行了封装,使得开发者在即使不了解 Material Design 的情况下也能轻松将自己的应用 Material 化。TabLayout 便是 Design Support 库中的一个全新控件。

TabLayout 允许开发者将标签指示器(Tab)与其对应的页面(一般为ViewPager)进行关联,达到切换标签指示器的同时,与它关联的页面也会跟着一起滑动的效果。如下图所示:


TabLayout + ViewPager + Fragment
二、TabLaout 单独使用
  1. 因为 TabLaout 位于 Design Support 库中,所以想要使用 TabLaout ,第一步便是在 app 的 build gradle 中引入 Design Support 库:
dependencies {
    ......
    implementation 'com.android.support:design:28.0.0-rc02'
}
  1. 编写 xml 布局:
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!--tabIndicatorColor:指示器的颜色-->
    <!--tabIndicatorHeight:指示器的高度,可设置为0,相当于没有指示器-->
    <!--tabTextColor:Tab未选中时字体的颜色-->
    <!--tabSelectedTextColor:Tab选中时字体的颜色-->
    <!--tabTextAppearance:Tab内文字的样式,TabLayout没有提供直接属性设置文字大小,需通过该属性指定style样式从而改变文字大小-->
    <!--tabMode:Tab的显示模式,默认为fixed(固定不能滑动,标签很多时会被挤压),可设置为scrollable(标签很多时可向左滑动)-->
    <!--tabGravity:内容的显示模式,可选center(居中)和fill(填充)-->
    <android.support.design.widget.TabLayout
        android:id="@+id/tl_main"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:tabIndicatorColor="@color/colorPrimaryDark"
        app:tabIndicatorHeight="3dp"
        app:tabTextColor="@android:color/black"
        app:tabSelectedTextColor="@color/colorPrimaryDark">
    </android.support.design.widget.TabLayout>

</LinearLayout>
  1. 编写对应Java代码
public class MainActivity extends AppCompatActivity {
    private TabLayout mTabLayout;

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

        mTabLayout = findViewById(R.id.tl_main);
        addTabToTabLayout();
    }

    /**
     * Description:给TabLayout添加tab,Tab.setIcon()方法可以给Tab添加图片
     */
    private void addTabToTabLayout() {
        String []mTitles = {"未支付账单", "支付中账单", "历史账单"};
        for (int i = 0; i < mTitles.length; i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(mTitles[i]));            
//          mTabLayout.addTab(mTabLayout.newTab().setText(mTitles[i]).setIcon(R.mipmap.ic_launcher));
        }
    }
}

效果图如下:


未使用 setIcon() 的 Tab

使用了 setIcon() 的 Tab
  1. 注意:
    TabLayout 没有直接提供设置 Tab 内字体大小的属性,需要通过 styles.xml 文件自定义一个 style 样式设置给 tabTextAppearance ,从而达到改变字体大小的目的。代码如下图所示:
<android.support.design.widget.TabLayout
    ......
    app:tabTextAppearance="@style/MyTabLayoutTextAppearance">
</android.support.design.widget.TabLayout>

对应的 style 代码如下所示:

<!--设置TabLayout内文字的字体大小-->
<style name="MyTabLayoutTextAppearance">
    <item name="android:textSize">18sp</item>
</style>

另外,当 TabLayout 的 tabMode 设置为 fixed 时,如果字体大小设置过大,会导致 Tab 显示异常,如下图:


Tab显示异常

解决办法可以通过适当缩减字体大小或者设置 tabMode 为 scrollable 。

三、TabLayout 结合 ViewPager 与 Fragment

TabLayout 单独使用的场景很少,它真正的强大之处在于可以结合 ViewPager 与 Fragment 共同使用,编写出精美的可滑动页面,常见于各种新闻、视频客户端。所以接下来就开始学习 TabLayout + ViewPager + Fragment 的使用吧。

  1. 编写 xml 布局:
    在 TabLayout 下面放入一个 ViewPager 作为 Fragment 的容器。
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
    <android.support.design.widget.TabLayout
        android:id="@+id/tl_main"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:tabIndicatorColor="@color/colorPrimaryDark"
        app:tabIndicatorHeight="3dp"
        app:tabTextColor="@android:color/black"
        app:tabSelectedTextColor="@color/colorPrimaryDark">
    </android.support.design.widget.TabLayout>
    
    <android.support.v4.view.ViewPager
        android:id="@+id/vp_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

</LinearLayout>
  1. 编写对应 Java 代码:
    先上 Activity 代码,较为简单,不做过多解释。
public class MainActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private String [] mTitles = {"未支付账单", "支付中账单", "历史账单"};
    private MyFragmentPagerAdapter mAdapter;
    private ViewPager mViewPager;

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

        mTabLayout = findViewById(R.id.tl_main);
        mViewPager = findViewById(R.id.vp_main);

        addTabToTabLayout();
        setupWithViewPager();
    }

    /**
     * Description:给TabLayout添加tab
     */
    private void addTabToTabLayout() {
        for (int i = 0; i < mTitles.length; i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(mTitles[i]));
        }
    }

    /**
     * Description:初始化FragmentPagerAdapter适配器并给ViewPager设置上该适配器,最后关联TabLayout和ViewPager
     */
    private void setupWithViewPager() {
        List<Fragment> mFragments = new ArrayList<>();
        mFragments.add(new FirstFragment());
        mFragments.add(new SecondFragment());
        mFragments.add(new ThirdFragment());

        mAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        mAdapter.addTitlesAndFragments(mTitles, mFragments);

        mViewPager.setAdapter(mAdapter); // 给ViewPager设置适配器
        mTabLayout.setupWithViewPager(mViewPager); //关联TabLayout和ViewPager
    }
}

然后是 ViewPager 的适配器代码。

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
    private String []titles;
    private List<Fragment> fragments;

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

    @Override
    public Fragment getItem(int i) {
        return fragments.get(i);
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    //自定义一个添加title和fragment的方法,供Activity使用
    public void addTitlesAndFragments(String []titles, List<Fragment> fragments) {
        this.titles = titles;
        this.fragments = fragments;
    }
}

最后是 Fragment 代码,较为简单,这里只贴出三个 Fragment 中的一个,对应的布局请随意,略过。

public class FirstFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.layout_fragment_first, null);
        return mView;
    }
}

最终效果图如下:


TabLayout + ViewPager + Fragment
四、TabLayout 第三方库 —— FlycoTabLayout

有时候官方 TabLayout 并不能满足实际开发需求,如想要改变 TabLayout 指示器的宽度,甚至设置指示器宽度和 Tab 内文字宽度一致,就会很麻烦,需要通过反射拿到 TabLayout 内的 TextView 对象并测量其宽度,最后通过 LayoutParams 设置给 TabLayout 。所以,各种第三方 TabLayout 库应运而生。

这里本人种草一波 FlycoTabLayout 库,该库集成了三种 TabLayout ,不同场景和需求下使用不同的库,可以高效且优雅地完成开发中各种五花八门的需求。该库功能强大,使用起来却又相当简单,你甚至不需要写 ViewPager 的适配器,仅一行代码就能关联 TabLayout 和 ViewPager 。想了解更多关于该库的介绍可以移步 github ,附上 github 地址:

https://github.com/H07000223/FlycoTabLayout

话不多说,接下来开始实践。

  1. 在 app 的 build gradle 中引入 FlycoTabLayout 库:
dependencies {
    ......
    implementation 'com.flyco.tablayout:FlycoTabLayout_Lib:2.1.2@aar'
}
  1. 编写 xml 布局:
    这里我使用了 FlycoTabLayout 库其中的 SlidingTabLayout ,实现 Tab 内指示器宽度与文本宽度一样的效果。
    同时可以看出,SlidingTabLayout 提供了专门的属性设置文本的字体大小,不用再像使用 TabLayout 时编写 style 属性了。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!--tl_indicator_color:指示器的颜色-->
    <!--tl_indicator_height:指示器的高度-->
    <!--tl_indicator_width:指示器的宽度-->
    <!--tl_textUnselectColor:Tab未选中时字体的颜色-->
    <!--tl_textSelectColor:Tab选中时字体的颜色-->
    <!--tl_textsize:字体大小-->
    <!--tl_indicator_width_equal_title:设置指示器宽度与文本宽度一致-->
    <!--tl_tab_space_equal:设置Tab大小等分-->
    <!--tl_divider_color:分割线的颜色-->
    <!--tl_divider_width:分割线的宽度-->
    <com.flyco.tablayout.SlidingTabLayout
        android:id="@+id/stl_main"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:tl_indicator_color="@color/colorPrimaryDark"
        app:tl_indicator_height="3dp"
        app:tl_textUnselectColor="@android:color/black"
        app:tl_textSelectColor="@color/colorPrimaryDark"
        app:tl_textsize="18sp"
        app:tl_indicator_width_equal_title="true"
        app:tl_tab_space_equal="true"
        app:tl_divider_color="@color/colorAccent"
        app:tl_divider_width="1dp">
    </com.flyco.tablayout.SlidingTabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>
</LinearLayout>
  1. 编写 Java 代码:
    在 Activity 内的使用就更简单了,真正实现一行代码解决问题,专治懒癌晚期患者。
public class MainActivity extends AppCompatActivity {
    private ViewPager mViewPager;
    private SlidingTabLayout slidingTabLayout;
    private ArrayList<Fragment> mFragments;;

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

        slidingTabLayout = findViewById(R.id.stl_main);
        mViewPager = findViewById(R.id.vp_main);
        mFragments = new ArrayList<>();
        mFragments.add(new FirstFragment());
        mFragments.add(new SecondFragment());
        mFragments.add(new ThirdFragment());
//      无需编写适配器,一行代码关联TabLayout与ViewPager
        slidingTabLayout.setViewPager(mViewPager, new String[]{"未支付账单", "支付中账单", "历史账单"}, this, mFragments);
    }
}
  1. 最终效果:


    SlidingTabLayout实现指示器与文本宽度一致



至此,关于 TabLayout 与 SlidingTabLayout 的简单使用就结束了。撒花!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容