tabLayout是種常見的頂部欄,他可以搭配viewPager來達成切換fragment的效果。
加入implementation
implementation 'com.google.android.material:material:1.2.0-alpha06'
在activity_main.xml加入一個tabLayout跟viewPager
<com.google.android.material.tabs.TabLayout
android:id="@+id/t_layout"
android:layout_width="match_parent"
android:layout_height="100dp"
app:tabMode="scrollable"
app:tabTextColor="@color/mainColor"
android:background="@color/dark"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/t_layout"
app:layout_constraintBottom_toBottomOf="parent"/>
建一個class取名VPagerAdapter,繼承FragmentPagerAdapter類別
class VPagerAdapter(f: FragmentManager, bh:Int) : FragmentPagerAdapter(f,bh){
override fun getItem(position: Int): Fragment {
return when(position){
0 -> ChestFragment() //第一頁要呈現的fragment(kt檔)
1 -> BackFragment() //第二頁要呈現的fragment(kt檔)
2 -> ShoulderFragment() //第三頁頁要呈現的fragment(kt檔)
3 -> TricepsFragment()
4 -> BicepsFragment()
5 -> LegsFragment()
else -> CoreFragment()
}
}
//自訂每個項目的title
override fun getPageTitle(position: Int): CharSequence {
when(position){
0 -> return "胸"
1 -> return "背"
2 -> return "肩膀"
3 -> return "三頭"
4 -> return "二頭"
5 -> return "臀腿"
else -> return "核心"
}
}
override fun getCount(): Int = 7 //直接回傳fragment頁數
在MainActivity連接adapter和viewPager
val adapter = VPagerAdapter(supportFragmentManager,7)
val tablayout = t_layout
val viewPager = view_pager
viewPager.adapter = adapter
//連動tablayout和viewPager
tablayout.setupWithViewPager(viewPager)