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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM