TabLayout是属于容器空间,提供水平显示Tab的效果,常常和ViewPager配合使用。

展示:

Android tab页切换 android tablayout viewpager_监听器

添加依赖

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

两种方式添加Tab

第一种:

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

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

public classMainActivityextendsAppCompatActivity{

    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;

    @Override
    protectedvoidonCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mTabLayout.addTab(mTabLayout.newTab().setText("首页"));
        mTabLayout.addTab(mTabLayout.newTab().setText("分类"));
        mTabLayout.addTab(mTabLayout.newTab().setText("设置"));
    }
}

第二种:
完全通过布局创建:

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

    <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="分类"
        />

    <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="设置"
        />

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

TabLayout属性

显示模式
可滑动
app:tabMode=”scrollable”
固定
app:tabMode=”fixed”

指示器选项
app:tabIndicatorHeight=”10dp” //指示器高度
app:tabIndicatorColor=”@color/colorPrimary” // 指示器颜色

文字选项
app:tabSelectedTextColor=”#ffffff” // 选择的Tab的文字颜色
app:tabTextColor=”#000000” // 未选择的Tab文字颜色
app:tabTextAppearance=”@style/Base.TextAppearance.AppCompat.Large” // 文字样式

背景设置
两者没什么区别
android:background=”@color/colorAccent” // 背景
app:tabBackground=”@color/colorPrimary” //背景

标签距离
app:tabPaddingStart=”10dp”
app:tabPaddingBottom=”10dp”
app:tabPadding=”10dp”
app:tabPaddingEnd=”10dp”
app:tabPaddingTop=”10dp”

对齐方式
居中显示
app:tabGravity=”center”
填充
app:tabGravity=”fill”

偏移

从左边开始偏移距离, 必须是可滑动的模式 scrollable

app:tabContentStart=”200dp”

Android tab页切换 android tablayout viewpager_ide_02

标签宽度限制
最大宽度
app:tabMaxWidth=”50dp”
最小宽度
app:tabMinWidth=”100dp”

TabLayout提供的方法

标签
创建标签
TabLayout.TabnewTab()
添加标签, 只有添加后才能显示

voidaddTab(TabLayout.Tab tab)

void addTab (TabLayout.Tab tab,
int position)

void addTab (TabLayout.Tab tab,
boolean setSelected)

void addTab (TabLayout.Tab tab,
int position,
boolean setSelected)

删除标签
voidremoveTab(TabLayout.Tab tab)

通过索引删除标签
voidremoveTabAt(intposition)

删除全部标签
voidremoveAllTabs()

得到标签
TabLayout.TabgetTabAt(intindex)

得到标签总数
intgetTabCount()

设置样式

指示器
voidsetSelectedTabIndicatorColor(intcolor)// 指示器颜色
void setSelectedTabIndicatorHeight (intheight) // 指示器高度

标签文本
voidsetTabTextColors(intnormalColor, // 正常颜色
int selectedColor) // 选择状态颜色
void setTabTextColors (ColorStateList textColor) // 状态颜色

显示模式
这个之前属性里面介绍过了

int getTabMode()
void setTabMode (intmode)
mode:
MODE_SCROLLABLE
MODE_FIXED

对齐方式
void setTabGravity(intgravity)
int getTabGravity ()

添加View
不止是添加标签Tab还可以直接添加View

void addView(View child)

void addView (View child,
int index)

void addView (View child,
ViewGroup.LayoutParams params)

void addView (View child, // View对象
int index, // 位置索引
ViewGroup.LayoutParams params) // 布局参数

得到当前选择的位置
intgetSelectedTabPosition()

监听器
选择监听器
该方法已经被废弃, 不推荐使用.
voidsetOnTabSelectedListener(TabLayout.OnTabSelectedListener listener)

替代的方法是
voidaddOnTabSelectedListener(TabLayout.OnTabSelectedListener listener)

该监听器用完后需要删除
voidremoveOnTabSelectedListener(TabLayout.OnTabSelectedListener listener)

一次性删除所有添加的选择监听器
voidclearOnTabSelectedListeners()


Tab

该类时TabLayout的内部类,表示TabLayout中的每一个标签

判断是否被选择
booleanisSelected()

设置为被选择状态
voidselect()

描述内容
如果你没用设置描述内容, 默认的是标签的标题

TabLayout.Tab setContentDescription(intresId)// 用strings id的
TabLayout.Tab setContentDescription (CharSequence contentDesc)
CharSequence getContentDescription ()

自定义标签的内容
每个标签可以尽情的自定义视图

TabLayout.TabsetCustomView(intresId)
TabLayout.Tab setCustomView (View view)

标签的标签
给Tab设置tag, 然后就可以通过tag得到Tab

TabLayout.TabsetTag(Object tag)
Object getTag ()

添加图标
TabLayout.Tab setIcon(Drawable icon)
TabLayout.Tab setIcon (intresId)
Drawable getIcon ()

标题的文字
TabLayout.TabsetText(intresId)
TabLayout.Tab setText (CharSequence text)
CharSequence getText ()

当前标签位置
intgetPosition()

关联ViewPager

Android tab页切换 android tablayout viewpager_viewpager_03

两者配合使用后TabLayout就不能通过自己创建Tab,需要PagerAdapter中实现getPagerTitle()方法返回标签的文字。标签的数量由ViewPager的分页数量决定

在布局中关联

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="vivian.com.tabandviewpager.MainActivity">

  <android.support.v4.view.ViewPager
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/viewpager"
      >
    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tab_layout"
        />

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


</LinearLayout>




public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = (TabLayout)findViewById(R.id.tab_layout);
        viewPager = (ViewPager)findViewById(R.id.viewpager);


        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {

            String[] titles = new String[]{"首页","分类","设置"};

            @Override
            public Fragment getItem(int position) {
                Log.d("position",String.valueOf(position));
                switch (position){
                    case 0:
                        return new Fragmentone();
                    case 1:
                        return new Fragmenttwo();
                    case 2:
                        return new Fragmentthree();
                }
                return null;
            }

            @Override
            public int getCount() {
                return 3;
            }

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



    }


}

Android tab页切换 android tablayout viewpager_监听器_04

如果没有在布局中关联,我们就需要在ViewPager设置Adapter之后进行关联
因为:

public void setupWithViewPager(ViewPager viewPager) {
    PagerAdapter adapter = viewPager.getAdapter();
    if(adapter == null) {
        throw new IllegalArgumentException("ViewPager does not have a PagerAdapter set");
    } else {
        ...
    }
}

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

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
mTabLayout.setupWithViewPager(mViewpager);

自定义TabLayout的样式

默认的情况下,TabLayout的tab indicator的颜色是Material Design中的accent color(#009688),我们可以稍作修改

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabIndicatorColor">#0000FF</item>
</style>

然后在布局中使用

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

其他样式参考:

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabMaxWidth">@dimen/tab_max_width</item>
    <item name="tabIndicatorColor">?attr/colorAccent</item>
    <item name="tabIndicatorHeight">2dp</item>
    <item name="tabPaddingStart">12dp</item>
    <item name="tabPaddingEnd">12dp</item>
    <item name="tabBackground">?attr/selectableItemBackground</item>
    <item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item>
    <item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>
<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?android:textColorSecondary</item>
    <item name="textAllCaps">true</item>
</style>

app:tabMode和app: tabGravity比较
android Material Design 中的TabLayout有两个比较有用的属性 app:tabMode、app:tabGravity。

(1)app:tabMode有两个值:fixed和scrollable。

(2)app:tabGravity有两个值:fill和center。

比较常用的是app:tabMode设置值scrollable,以及app:tabGravity设置值center。

比如,当app:tabMode设置值scrollable表示此TabLayout中当子view超出屏幕边界时候,将提供滑动以便滑出不可见的那些子view。

而app:tabGravity设置值center,在有些情况下,比如TabLayout中子view较少需要居中显示时候的情景。

现在给出一个例子加以说明。

1)tabGravity=”fill”和tabMode=”fixed”

Android tab页切换 android tablayout viewpager_viewpager_05


2)tabGravity=”center”和tabMode=”fixed”

Android tab页切换 android tablayout viewpager_Android tab页切换_06


3)tabGravity=”fill”和tabMode=”scrollable”

Android tab页切换 android tablayout viewpager_ide_07

4)tabGravity=”cente”和tabMode=”scrollable”

Android tab页切换 android tablayout viewpager_监听器_08


自定义view到Tab

在适配器中增加getTabView(。。。)方法:

class fragAdapter extends FragmentPagerAdapter{
            String[] titles = new String[]{"首页","分类","设置"};
            private int[] images = {
                    R.mipmap.ic_launcher,
                    R.mipmap.ic_launcher,
                    R.mipmap.ic_launcher
            };

            Context context;

            public fragAdapter(FragmentManager fm, Context context) {
                super(fm);
                this.context = context;
            }

            @Override
            public Fragment getItem(int position) {
                Log.d("position",String.valueOf(position));
                switch (position){
                    case 0:
                        return new Fragmentone();
                    case 1:
                        return new Fragmenttwo();
                    case 2:
                        return new Fragmentthree();
                }
                return null;
            }

            @Override
            public int getCount() {
                return 3;
            }

            @Override
            public CharSequence getPageTitle(int position) {
//                Drawable image = ContextCompat.getDrawable(context,images[0]);
//                image.setBounds(0,0,image.getIntrinsicWidth(),image.getIntrinsicHeight());
//                SpannableString sb = new SpannableString("   ");
//                ImageSpan imageSpan = new ImageSpan(image,ImageSpan.ALIGN_BOTTOM);
//                sb.setSpan(imageSpan,0,3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//
//                return sb;
            return null;

            }

            public View getTabView(int position){
                View view = LayoutInflater.from(context).inflate(R.layout.tabview,null);
                TextView textView = (TextView)view.findViewById(R.id.textView);
                ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
                textView.setText(titles[position]);
                imageView.setImageResource(images[position]);
                return view;
            }


        }

使用:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        adapter = new fragAdapter(getSupportFragmentManager(),this);

        viewPager.setAdapter(adapter) ;
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        for(int i =0;i<tabLayout.getTabCount();i++){
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(adapter.getTabView(i));
        }

效果:

Android tab页切换 android tablayout viewpager_Android tab页切换_09

注意:要自定义Tab,TabLayout和ViewPager不能再布局中关联,否则显示不出来

本篇参考于:

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0731/3247.html#commettop

后两篇关于直接设置icon的,我实现不了,不知道原因