TabLayout的使用
用于展示Tab的控件
1基本的使用方式
-
通過(guò)xml設(shè)置
<android.support.design.widget.TabLayout android:id="@+id/tl" android:layout_width="match_parent" android:layout_height="45dp"> <android.support.design.widget.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab1"/> <android.support.design.widget.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab2"/> <android.support.design.widget.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab3"/> </android.support.design.widget.TabLayout>
-
通過(guò)代碼設(shè)置條目
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
-
一些基本參數(shù)設(shè)置
- app:tabSelectedTextColor 設(shè)置選中字體的顏色
- app:tabTextColor 未選中字體的顏色
- app:tabIndicatorColor 設(shè)置指示器下標(biāo)的顏色
- app:tabBackground 整個(gè)TabLayout的顏色
- app:tabIndicatorHeight 設(shè)置指示器下標(biāo)的高度(這里如果設(shè)置成0的時(shí)候就是沒(méi)有底部的下劃線了)
- app:tabMode Tab的模式(后面會(huì)詳細(xì)說(shuō)明)
- app:tabPadding 設(shè)置Tab內(nèi)部的子控件的Padding
- app:tabGravity 內(nèi)容的顯示模式
2改變TabLayout的內(nèi)部字體大小
app:tabTextAppearance="@android:style/TextAppearance.Holo.Large"http://設(shè)置文字的外貌
3添加圖標(biāo)
tabLayout.addTab(tabLayout.newTab().setText("Tab 1").setIcon(R.mipmap.ic_launcher));
4Tab模式
- fixed 固定的,標(biāo)簽多的時(shí)候會(huì)被擠壓,并且不能滑動(dòng)
- scrollable 非固定的,標(biāo)簽多的時(shí)候能滑動(dòng)
5TabLayout的監(jiān)聽(tīng)(addOnTabSelectedListener)
- onTabSelected(TabLayout.Tab tab) 選中了Tab的邏輯
- onTabUnselected(TabLayout.Tab tab) 未選中Tab的邏輯
- onTabReselected(TabLayout.Tab tab) 再次選中Tab的邏輯
6和ViewPager聯(lián)動(dòng)
tabLayout.setupWithViewPager(Viewpager); (這里注意一點(diǎn),當(dāng)和ViewPager聯(lián)動(dòng)的時(shí)候要重寫getPageTitle這個(gè)方法設(shè)置Tab的標(biāo)題)
7默認(rèn)選中某項(xiàng)
tabLayout.getTabAt(position).select();