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寬度 |
使用,添加選項
- 靜態創建(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>
- 動態創建(使用java代碼添加tab)
先是通過findviewbyid
方法找到實例,之後調用tablayout
的newTab
方法來創建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];
}