结构
布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/view_pager2"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tab_layout" />
</androidx.constraintlayout.widget.ConstraintLayout>
逻辑代码
1.Adapter
自定义一个继承于FragmentStateAdapter的adapter类,将其实例复制给viewPager的adaper属性
class SectionPagerAdapter(fragment: Fragment, private val fragmentList: List<Fragment>): FragmentStateAdapter(fragment) {
override fun getItemCount(): Int = fragmentList.size
override fun createFragment(position: Int): Fragment = fragmentList[position]
}
2.Fragment页面
以下只写了关键代码
???注意:一定要在viewPager2设置好adapter2之后再调用attach()
private lateinit var tabLayout: TabLayout
private var tabTitle: MutableList<String> = ArrayList()
private lateinit var viewPager2: ViewPager2
private var fragmentList: MutableList<Fragment> = ArrayList()
private fun initLayout() {
tabTitle.apply {
add(resources.getString(R.string.nav_timer_top_count_up))
add(resources.getString(R.string.nav_timer_top_count_down))
add(resources.getString(R.string.nav_timer_top_important_day))
}
fragmentList.apply {
add(CountUpFragment())
add(CountDownFragment())
add(ImportantDayFragment())
}
viewPager2.adapter = SectionPagerAdapter(this, fragmentList)
TabLayoutMediator(tabLayout,viewPager2){ tab, position ->
tab.text = tabTitle[position]
}.attach()
}
|