1、添加庫
compile 'com.android.support:design:25.1.0'
2、添加布局
1 <android.support.design.widget.TabLayout 2 android:id="@+id/id_tablayout" 3 android:layout_width="match_parent" 4 android:layout_height="wrap_content" 5 /> 6 7 <!-- 其他屬性: 8 改變選中字體的顏色 9 app:tabSelectedTextColor="@android:color/holo_orange_light" 10 11 改變未選中字體的顏色 12 app:tabTextColor="@color/colorPrimary" 13 14 改變指示器下標的顏色 15 app:tabIndicatorColor="@android:color/holo_orange_light" 16 17 改變整個TabLayout的顏色 18 app:tabBackground="color" 19 20 設置文字的外貌 21 app:tabTextAppearance="@android:style/TextAppearance.Holo.Large" 22 23 設置指示器下標的厚度 24 app:tabIndicatorHeight="4dp" 25 26 當Tab很多時,如此設置即可滑動 27 app:tabMode="scrollable" (默認是鋪滿 FIXED) 28 29 設置tab顯示模式 此為居中,如果是fill,則是充滿 30 app:tabGravity="center" 31 32 設置最大的tab寬度 33 app:tabMaxWidth="xxdp" 34 35 最小的tab寬度 36 app:tabMinWidth="xxdp" 37 38 39 -->
注意:需要將主題設置為android:theme="@style/Theme.AppCompat"
3、findViewById實例化后,添加tab
方法一:
通過TabLayout的addTab()方法添加新構建的Tab實例到TabLayout中:
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
方法二:
通過viewPager結合使用
tabLayout.setupWithViewPager(viewPager); //將viewpager直接綁定到tablayout上即可,viewpager有幾個頁面就有幾個tab //設置tab上的標題可以 tabLayout.getTabAt(i).setText(tabs[i]); //也可以在 FragmentPagerAdapter 上重寫方法 public CharSequence getPageTitle(int position) @Override public CharSequence getPageTitle(int position) { return titleList.get(position); }
