Android 顶部导航栏(TabLayout+ViewPager2)

文章目录

  • 结构
  • 布局
  • 逻辑代码
    • 1.Adapter
    • 2.Fragment页面

结构

Android 顶部导航栏(TabLayout+ViewPager2)_第1张图片

布局


<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() {
    //设置TabLayout标题
    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))
    }
    //设置fragment
    fragmentList.apply {
        add(CountUpFragment())
        add(CountDownFragment())
        add(ImportantDayFragment())
    }
    //绑定adapter
    viewPager2.adapter = SectionPagerAdapter(this, fragmentList)
    //连接TabLayout和ViewPager2
    TabLayoutMediator(tabLayout,viewPager2){ tab, position -> 
                                            tab.text = tabTitle[position]
                                           }.attach()
}

你可能感兴趣的:(android,android,kotlin,开发语言)