Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱
MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina.com

目录

TabLayout 简介

文档简介

文档位置

依赖

  1. implementation 'com.android.support:design:28.0.0'

继承体系

  1. java.lang.Object
  2. android.view.View
  3. android.view.ViewGroup
  4. android.widget.FrameLayout
  5. android.widget.HorizontalScrollView
  6. android.support.design.widget.TabLayout

TabLayout provides a horizontal layout to display tabs.

TabLayout提供水平布局以显示选项卡。

Population of the tabs to display is done through TabLayout.Tab instances. You create tabs via newTab(). From there you can change the tab's label or icon via setText(int) and setIcon(int) respectively. To display the tab, you need to add it to the layout via one of the addTab(Tab) methods.

要显示的选项卡的填充是通过TabLayout.Tab实例完成的。 您可以通过newTab()创建选项卡。 从那里,您可以分别通过setText(int)setIcon(int)更改选项卡的标签或图标。 要显示选项卡,需要通过addTab(Tab)方法之一将其添加到布局中。

You should set a listener via setOnTabSelectedListener(OnTabSelectedListener) to be notified when any tab's selection state has been changed.

您应该通过setOnTabSelectedListener设置一个侦听器,以便在任何选项卡的选择状态发生更改时得到通知。

You can also add items to TabLayout in your layout through the use of TabItem.

您还可以通过使用TabItem将项目添加到布局中的TabLayout。

If you're using a ViewPager together with this layout, you can call setupWithViewPager(ViewPager) to link the two together. This layout will be automatically populated from the PagerAdapter's page titles.

如果您将ViewPager与此布局一起使用,则可以调用setupWithViewPager(ViewPager)将两者链接在一起。 此布局将自动从PagerAdapter的页面标题中填充

This view also supports being used as part of a ViewPager's decor, and can be added directly to the ViewPager in a layout resource file like so:

此视图还支持用作ViewPager的装饰的一部分,并且可以直接添加到布局资源文件中的ViewPager,如下所示:

  1. <android.support.v4.view.ViewPager
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent">
  4. <android.support.design.widget.TabLayout
  5. android:layout_width="match_parent"
  6. android:layout_height="wrap_content"
  7. android:layout_gravity="top" />
  8. </android.support.v4.view.ViewPager>

注,和ViewPager联合使用时,TabLayout 可以作为 ViewPager 的子元素,也可以单独让在任何地方。

通过调用TabLayout的setupWithViewPager方法便可实现TabLayout与ViewPager的联动。看源码可以知道,其是通ViewPager的OnPageChangeListener监听将两者连接起来的。

内部类和内部接口

唯一的一个内部接口:TabLayout.OnTabSelectedListener

Callback interface invoked when a tab's selection state changes. Some applications may use this action to return to the top level of a category类型.

  • onTabReselected(TabLayout.Tab tab) Called when a tab that is already selected is chosen again by the user.
  • onTabSelected(TabLayout.Tab tab) Called when a tab enters the selected state.
  • onTabUnselected(TabLayout.Tab tab) Called when a tab exits the selected state.

内部类:TabLayout.ViewPagerOnTabSelectedListener

A TabLayout.OnTabSelectedListener class which contains the necessary calls back to the provided ViewPager so that the tab position is kept in sync.

  1. public static class TabLayout.ViewPagerOnTabSelectedListener extends Object implements TabLayout.OnTabSelectedListener

内部类:TabLayout.TabLayoutOnPageChangeListener

A ViewPager.OnPageChangeListener class which contains the necessary calls back to the provided TabLayout so that the tab position is kept in sync.

  1. public static class TabLayout.TabLayoutOnPageChangeListener extends Object implements ViewPager.OnPageChangeListener

This class stores the provided TabLayout weakly, meaning that you can use addOnPageChangeListener(OnPageChangeListener) without removing the listener and not cause a leak.

内部类:TabLayout.Tab

A tab in this layout. Instances can be created via newTab().

  • CharSequence getContentDescription() Gets a brief description of this tab's content for use in accessibility support.
  • View getCustomView() Returns the custom view used for this tab.
  • Drawable getIcon() Return the icon associated with this tab.
  • int getPosition() Return the current position of this tab in the action bar.
  • Object getTag() CharSequence getText() Return the text of this tab.
  • boolean isSelected() Returns true if this tab is currently selected.
  • void select() Select this tab.
  • TabLayout.Tab setContentDescription(int resId 或 CharSequence contentDesc) Set a description of this tab's content for use in accessibility support.
  • TabLayout.Tab setCustomView(int resId 或 View view) Set a custom view to be used for this tab.
  • TabLayout.Tab setIcon(int resId 或 Drawable icon) Set the icon displayed on this tab.
  • TabLayout.Tab setText(int resId 或 CharSequence text) Set the text displayed on this tab.
  • TabLayout.Tab setTag(Object tag) Give this Tab an arbitrary object to hold for later use.

XML attributes

特有的属性:

  • android.support.design:tabBackground Reference to a background to be applied to tabs.
  • android.support.design:tabContentStart Position in the Y axis from the starting edge that tabs should be positioned from.
  • android.support.design:tabGravity Gravity constant for tabs.
  • android.support.design:tabIndicatorColor / tabIndicatorHeight Color of the indicator used to show the currently selected tab.
  • android.support.design:tabMaxWidth / tabMinWidth The maximum width for tabs.
  • android.support.design:tabMode The behavior mode for the Tabs in this layout
  • android.support.design:tabPadding / tabPaddingBottom / ... The preferred padding along all edges of tabs.
  • android.support.design:tabSelectedTextColor / tabTextColor The text color to be applied to the currently selected tab.
  • android.support.design:tabTextAppearance A reference to a TextAppearance style to be applied to tabs.

公共方法

添加移除OnTabSelectedListener

  • void addOnTabSelectedListener(TabLayout.OnTabSelectedListener listener) Add a TabLayout.OnTabSelectedListener that will be invoked when tab selection changes.
  • void removeOnTabSelectedListener(TabLayout.OnTabSelectedListener listener) Remove the given TabLayout.OnTabSelectedListener that was previously added via addOnTabSelectedListener(OnTabSelectedListener).
  • void clearOnTabSelectedListeners() Remove all previously added TabLayout.OnTabSelectedListeners.
  • void setOnTabSelectedListener(TabLayout.OnTabSelectedListener listener) This method was deprecated in API level 24.0.0.

添加移除Tab

  • void addTab(TabLayout.Tab tab, boolean setSelected) Add a tab to this layout. The tab will be added at the end of the list.
  • void addTab(TabLayout.Tab tab, int position) Add a tab to this layout. The tab will be inserted at position. If this is the first tab to be added it will become the selected tab.
  • void addTab(TabLayout.Tab tab) Add a tab to this layout. The tab will be added at the end of the list. If this is the first tab to be added it will become the selected tab.
  • void addTab(TabLayout.Tab tab, int position, boolean setSelected)
  • void removeAllTabs() Remove all tabs from the action bar and deselect the current tab.
  • void removeTabAt(int position) Remove a tab from the layout. If the removed tab was selected it will be deselected and another tab will be selected if present.
  • void removeTab(TabLayout.Tab tab) Remove a tab from the layout.

获取、创建Tab

  • TabLayout.Tab getTabAt(int index) Returns the tab at the specified index.
  • TabLayout.Tab newTab() Create and return a new TabLayout.Tab.

获取Tab位置、数量

  • int getSelectedTabPosition() Returns the position of the current selected tab.
  • int getTabCount() Returns the number of tabs currently registered with the action bar.

设置Tab样式

这些样式全可以在xml中设置,有很多样式只能在xml中设置

  • void setSelectedTabIndicatorColor(int color) Sets the tab indicator's color for the currently selected tab.
  • void setSelectedTabIndicatorHeight(int height) Sets the tab indicator's height for the currently selected tab.
  • void setTabGravity(int gravity) / getTabGravity Set the gravity to use when laying out the tabs.
  • void setTabMode(int mode) / getTabMode Set the behavior mode for the Tabs in this layout.
  • void setTabTextColors(int normalColor, int selectedColor) Sets the text colors for the different states (normal, selected) used for the tabs.
  • void setTabTextColors(ColorStateList textColor) / getTabTextColors Sets the text colors for the different states (normal, selected) used for the tabs.

添加子View

  • void addView(View child, int index) Adds a child view. If no layout parameters are already set on the child, the default parameters for this ViewGroup are set on the child.
  • void addView(View child)
  • void addView(View child, ViewGroup.LayoutParams params) Adds a child view with the specified layout parameters.
  • void addView(View child, int index, ViewGroup.LayoutParams params) Adds a child view with the specified layout parameters.

与ViewPager联动

  • void setupWithViewPager(ViewPager viewPager) The one-stop shop for setting up this TabLayout with a ViewPager.
  • void setupWithViewPager(ViewPager viewPager, boolean autoRefresh)
  • void setTabsFromPagerAdapter(PagerAdapter adapter) This method was deprecated in API level 23.2.0.

其他

  • FrameLayout.LayoutParams generateLayoutParams(AttributeSet attrs) Returns a new set of layout parameters based on the supplied attributes set.
  • void setScrollPosition(int position, float positionOffset, boolean updateSelectedText) Set the scroll position of the tabs. This is useful for when the tabs are being displayed as part of a scrolling container such as ViewPager .Calling this method does not update the selected tab, it is only used for drawing purposes.
  • boolean shouldDelayChildPressedState() Return true if the pressed state should be delayed for children or descendants of this ViewGroup.

两种模式

MODE_FIXED

Fixed tabs display all tabs concurrently and are best used with content that benefits from quick pivots between tabs. The maximum number of tabs is limited by the view’s width. Fixed tabs have equal width, based on the widest tab label.

固定选项卡同时显示所有选项卡,最适用于受益于选项卡之间快速枢轴的内容。 选项卡的最大数量受视图宽度的限制。 固定标签的宽度相等,基于最宽的标签标签。

MODE_SCROLLABLE

Scrollable tabs display a subset of tabs at any given moment, and can contain longer tab labels and a larger number of tabs. They are best used for browsing contexts in touch interfaces when users don’t need to directly compare the tab labels.

可滚动选项卡在任何给定时刻显示选项卡的子集,并且可以包含更长的选项卡标签和更多数量的选项卡。 当用户不需要直接比较标签时,它们最适合用于浏览触摸界面中的内容。

默认样式

TabLayout的默认样式

  1. app:theme="@style/Widget.Design.TabLayout"
  1. <style name="Widget.Design.TabLayout" parent="Base.Widget.Design.TabLayout">
  2. <item name="tabGravity">fill</item>
  3. <item name="tabMode">fixed</item>
  4. </style>
  1. <style name="Base.Widget.Design.TabLayout" parent="android:Widget">
  2. <item name="tabMaxWidth">@dimen/design_tab_max_width</item>【264dp】
  3. <item name="tabIndicatorColor">?attr/colorAccent</item>
  4. <item name="tabIndicatorHeight">2dp</item>
  5. <item name="tabPaddingStart">12dp</item>
  6. <item name="tabPaddingEnd">12dp</item>
  7. <item name="tabBackground">?attr/selectableItemBackground</item>
  8. <item name="tabTextAppearance">@style/TextAppearance.Design.Tab</item>
  9. <item name="tabSelectedTextColor">?android:textColorPrimary</item>
  10. </style>

我们可以改变TabLayout对应的系统样式的属性值来适配我们自己的需求。

Tab文本的默认样式

  1. <style name="TextAppearance.Design.Tab" parent="TextAppearance.AppCompat.Button">
  2. <item name="android:textSize">@dimen/design_tab_text_size</item>
  3. <item name="android:textColor">?android:textColorSecondary</item>
  4. <item name="textAllCaps">true</item>【1、全部大写显示;2、可能导致无法显示某些内容】
  5. </style>

测试代码

完整Demo地址

Activity

  1. public class SimpleTestActivity extends FragmentActivity {
  2. private String[] titles = {"包青天", "白", "bqt注意字母的大小写", "白乾涛", "1", "广州玖拾玖度信息科技有限公司广州东百科技有限公司", "bqt"};
  3. ViewPager viewPager, viewPager2;
  4. TabLayout tabLayout, tabLayout2;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9. viewPager = findViewById(R.id.view_pager);
  10. viewPager2 = findViewById(R.id.view_pager2);
  11. viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()));
  12. viewPager2.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()));
  13. //在代码中设置属性,也可以在XML中设置(推荐),不多大多都没什么卵用
  14. tabLayout = findViewById(R.id.tablayout);
  15. tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);//滚动模式,根据内容自动调整宽度,不管内容多长都全部显示且不换行
  16. tabLayout.setTabGravity(Gravity.TOP);//没卵用!
  17. tabLayout.setTabTextColors(Color.RED, Color.GREEN); //正常、选中的颜色
  18. tabLayout.setSelectedTabIndicatorColor(Color.BLUE); //下划线颜色
  19. tabLayout.setSelectedTabIndicatorHeight(15); //下划线
  20. tabLayout.setBackgroundColor(Color.YELLOW); //背景色,设置选择器不起效果!
  21. tabLayout.setupWithViewPager(viewPager);
  22. //在XML中设置Tab样式
  23. tabLayout2 = findViewById(R.id.tablayout2);
  24. tabLayout2.setTabMode(TabLayout.MODE_FIXED);//固定模式,会将每个tab都显示出来,tab的宽度一样,内容太长会换行及显示...
  25. tabLayout2.setupWithViewPager(viewPager2);
  26. }
  27. class MyFragmentPagerAdapter extends FragmentPagerAdapter {
  28. MyFragmentPagerAdapter(FragmentManager fm) {
  29. super(fm);
  30. }
  31. @Override
  32. public Fragment getItem(int position) {
  33. return MyFragment.newInstance(titles[position]);
  34. }
  35. @Override
  36. public int getCount() {
  37. return titles.length;
  38. }
  39. @Override
  40. public CharSequence getPageTitle(int position) {
  41. return titles[position];//虽然不是抽象方法,但是必须重写,不重写的话会导致TabLayout没有标题
  42. }
  43. }
  44. }

XML布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:orientation="vertical">
  8. <android.support.design.widget.TabLayout
  9. android:id="@+id/tablayout"
  10. android:layout_width="match_parent"
  11. android:layout_height="wrap_content"
  12. app:theme="@style/Widget.Design.TabLayout"/>
  13. <android.support.v4.view.ViewPager
  14. android:id="@+id/view_pager"
  15. android:layout_width="match_parent"
  16. android:layout_height="200dp"
  17. android:layout_below="@id/tablayout"/>
  18. <android.support.v4.view.ViewPager
  19. android:id="@+id/view_pager2"
  20. android:layout_width="match_parent"
  21. android:layout_height="match_parent"
  22. android:layout_above="@id/tablayout2"
  23. android:layout_below="@id/view_pager"/>
  24. <android.support.design.widget.TabLayout
  25. android:id="@+id/tablayout2"
  26. style="@style/MyTabStyle"
  27. android:layout_width="match_parent"
  28. android:layout_height="wrap_content"
  29. android:layout_alignParentBottom="true"
  30. app:tabTextAppearance="@style/MyTabTextAppearance"/>
  31. </RelativeLayout>

定义的样式

Tab样式

  1. <style name="MyTabStyle" parent="Widget.Design.TabLayout">
  2. <item name="android:background">@android:color/holo_green_dark</item><!--此背景会被tabBackground覆盖掉-->
  3. <item name="tabBackground">@android:color/holo_orange_dark</item><!--"通常"和background的效果完全一样-->
  4. <item name="tabContentStart">20dp</item><!--此值导致左边一块区域属于background,但不属于tabBackground-->
  5. <item name="tabGravity">fill</item><!--只能是fill或center,貌似没有卵用啊-->
  6. <item name="tabIndicatorHeight">5dp</item>
  7. <item name="tabIndicatorColor">#f00</item>
  8. <item name="tabMaxWidth">120dp</item>
  9. <item name="tabMinWidth">20dp</item>
  10. <item name="tabPadding">0dp</item>
  11. <item name="tabMode">scrollable</item>
  12. <item name="tabSelectedTextColor">#f00</item>
  13. <!--以下属性貌似都无效!-->
  14. <item name="android:ellipsize">end</item>
  15. <item name="android:maxLines">1</item>
  16. <item name="android:gravity">top</item>
  17. <item name="android:textColor">#fff</item>
  18. </style>

Tab文字样式

  1. <style name="MyTabTextAppearance" parent="TextAppearance.Design.Tab"><!--必须继承自TextAppearance.Design.Tab -->
  2. <!--只支持以下三个属性-->
  3. <item name="android:textSize">15sp</item>
  4. <item name="android:textAllCaps">false</item>
  5. <!--选择器无效!除非根据tab的选中状态手动设置-->
  6. <item name="android:textColor">@drawable/sel_tab_textcolor</item>
  7. </style>

2017-6-28

TabLayout ViewPager Fragment 简介 案例 MD的更多相关文章

  1. [置顶] xamarin Tablayout+Viewpager+Fragment顶部导航栏

    最近几天不忙,所以把项目中的顶部导航栏的实现归集一下.android中使用TabLayout+ViewPager+Fragment制作顶部导航非常常见,代码实现也比较简单.当然我这个导航栏是基于xam ...

  2. Android开发之漫漫长途 Fragment番外篇——TabLayout+ViewPager+Fragment

    该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...

  3. LruCache DiskLruCache 缓存 简介 案例 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  4. 关于tablayout+viewpager+fragment配合使用的一点记录

    最近在写项目的时候遇到要求使用tablayout和fragment,遇到了这里记录一下大致思路. tablayout是头部可以左右切换的头部控制栏控件,配合viewpager使用,fragment是碎 ...

  5. protobuf Protocol Buffers 简介 案例 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  6. 集合 enum 枚举 简介 案例 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  7. TabLayout+ViewPager+Fragment制作页卡

    本人很懒,直接上代码了. 布局文件: <?xml version="1.0" encoding="utf-8"?><android.suppo ...

  8. Javassist 字节码 简介 案例 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  9. 安卓TabLayout+ViewPager实现切页

    安卓使用TabLayout+ViewPager+Fragment 实现页面切换,可实现左右滑动切换视图界面和点击切换 可自定义菜单栏是在顶部还是在底部 一.实现效果: 二.实现过程: 2.1 一些重要 ...

随机推荐

  1. Java 中的数据类型

    我们学习Java就是为了编写程序完成功能,而什么是程序呢?程序 = 数据结构 + 算法. 分开看,数据结构指的是数据与数据之间的关系,那我们先来了解一下Java中的数据都是怎么表示的呢 ?也就是说数据 ...

  2. 高并发编程之synchronized

    一.什么是线程? 线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元.一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成.另外,线程 ...

  3. C#管理windows服务

    .NET Framework中提供了现成的类库可以很方便的实现对windows服务的安装.卸载.启动.停止.获取运行状态等功能.这些类都在System.ServiceProcess命名空间下. 安装w ...

  4. Struts2 (中)

    Struts中API介绍 ServletAPI 在使用Struts2的框架的过程中,发现Struts2和Servlet的API是解耦合的. 在实际开发中,经常使用到Servlet的API,比如进行登录 ...

  5. hdu 1325 判断有向图是否为树

    题意:判断有向图是否为树 链接:点我 这题用并查集判断连通,连通后有且仅有1个入度为0,其余入度为1,就是树了 #include<cstdio> #include<iostream& ...

  6. 无法将类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的COM 对象强制转换为接口类型“Microsoft.Office.Interop.Excel._Application”

    报错内容如下: 无法将类型为“Microsoft.Office.Interop.Excel.ApplicationClass”的COM对象强制转换为接口类型“Microsoft.Office.Inte ...

  7. Linux知识(7)----远程登录 和远程拷贝

    一.远程登录 1.安装客户端 可以使用ssh(Secure Shell(缩写为SSH))来进行远程的登录.安装ssh的命令为: sudo apt-get install openssh-server ...

  8. 二值化方法:Kittler:Minimum Error Thresholding

    Kittler二值化方法,是一种经典的基于直方图的二值化方法.由J. Kittler在1986年发表的论文“Minimum Error Thresholding”提出.论文是对贝叶斯最小错误阈值的准则 ...

  9. vue父子组件使用时遇到的一个问题

    子组件一定要写在父组件之前,例如: //子vue,这里遇到一个坑,那就是子vue一定要写在父vue前面,不然会报错. Vue.component('todo-item', { template: $( ...

  10. Mac下操作mysql

    修改密码 进入到mysql工作目录 cd /usr/local/mysql/bin/ 登录mysql mysql -u root -p 输入初始密码 mysql> 设置新密码 mysql> ...