Android开发—— Tablayout的使用

Tablayout的使用

属性

属性名 说明
app:tabMod 设置Tab模式
app:tabTextColor 设置文本颜色
app:tabSelectedTextColor 设置选中文本颜色
app:tabIndicatorColor 设置下滑条颜色
app:tabMaxWidth="xxdp" 设置最大的tab宽度
app:tabMinWidth="xxdp" 设置最小的tab宽度

使用,添加选项

  1. 静态创建(xml文件中添加tab)

效果:

添加一个tabitem即可,之后设置相关的属性,

<android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        app:tabTextColor="@color/colorAccent"
        app:tabSelectedTextColor="@color/colorPrimary"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabMode="fixed"
        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.TabLayout>
  1. 动态创建(使用java代码添加tab)

先是通过findviewbyid方法找到实例,之后调用tablayoutnewTab方法来创建tab

		TabLayout.Tab tab1 = mTablayout.newTab();
        tab1.setText("正在下载");
        mTablayout.addTab(tab1,0);
        tab1 = mTablayout.newTab();
        tab1.setText("已下载");
        mTablayout.addTab(tab1,1);

不过,使用动态的话,如果不设置相关的属性,是不能达到两个选项各自占长度一半,还得给Tablayout加上下列属性

            app:tabMaxWidth="0dp"
            app:tabGravity="fill"
            app:tabMode="fixed"

Tablayout与Viewpager联用

一句代码即可搞定

tabLayout.setupWithViewPager(Viewpager);

有些时候可能会出现不显示文本的情况,这时候需要在 PagerAdapter 里面重写一个方法

String[] titles ={"tab1","tab2"};
@Override
public CharSequence getPageTitle(int position) {
    return mStrings[position];
}

参考

Tablayout

posted @ 2019-02-22 13:20  Stars-one  阅读(9701)  评论(0编辑  收藏  举报