欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android开发—— Tablayout的使用

程序员文章站 2023-02-20 23:46:24
Tablayout的使用 属性 |属性名 | 说明| | | | |app:tabMod |设置Tab模式 | |app:tabTextColor |设置文本颜色 | |app:tabSelectedTextColor |设置选中文本颜色 | |app:tabIndicatorColor |设置下滑 ......

tablayout的使用

属性

属性名 说明
app:tabmod 设置tab模式
app:tabtextcolor 设置文本颜色
app:tabselectedtextcolor 设置选中文本颜色
app:tabindicatorcolor 设置下滑条颜色
app:tabmaxwidth="xxdp" 设置最大的tab宽度
app:tabminwidth="xxdp" 设置最小的tab宽度

使用,添加选项

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

效果:

Android开发—— Tablayout的使用

添加一个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