Material Design-TabLayout和ViewPager2

周朗
2023-12-01

TabLayout

  • xml
<com.google.android.material.tabs.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/teal_700"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar2"
        app:tabIndicatorColor="@android:color/holo_red_dark"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@android:color/holo_red_dark"
        app:tabTextColor="@android:color/white" />

app:tabIndicatorColor 设置指示器的颜色

app:tabMode=“scrollable” 设置滑动的模式,fix表示固定,数量多了会压缩。scrollable表示可滑动的

app:tabSelectedTextColor 选中的文字颜色

  • tabLayot添加多个tab
val titles = listOf<String>(
  "精选", "体育", "巴萨", "购物", "明星", "视频", "健康",
  "励志", "图文", "本地", "动漫", "搞笑"
)
titles.forEach {
  //创建tab
  val newTab = tabLayout.newTab()
  newTab.text = it
  tabLayout.addTab(newTab)
}

给tablayout设置样式

    <style name="tabTextStyle" parent="TextAppearance.Design.Tab">
        <item name="textAllCaps">false</item>
    </style>
app:tabTextAppearance="@style/tabTextStyle"

设置自定义view

private fun initTabLayout(tablayout: TabLayout) {
  val tabNames = resources.getStringArray(R.array.tab_names)

  tabNames.forEachIndexed { index, content ->
                           val tab = tablayout.newTab()
                           val textView = TextView(this)

                           textView.setTextColor(resources.getColorStateList(R.color.selector_tab_text))
                           textView.textSize = if (index == 0) 20f else 16f
                           textView.typeface = Typeface.DEFAULT_BOLD
                           textView.text = content
                           textView.gravity = Gravity.CENTER
                           tab.customView = textView
                           tablayout.addTab(tab)
                          }


  tablayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    override fun onTabSelected(tab: TabLayout.Tab?) {
      tab ?: return
      val textView = tab.customView as? TextView
      textView?.textSize = 20f
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
      tab ?: return
      val textView = tab.customView as? TextView
      textView?.textSize = 16f
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
    }
  })
}

当tabLayout和ViewPager2关联时,上面手动添加tab无效,需要在TabLayoutMediator中设置tab的view

ViewPager2

  • xml
<androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tablayout" />

android:orientation 设置viewpager2的滑动方向

  • 代码设置
//设置viewpager2的方向,在xml中也可以设置
viewPager2.orientation = ViewPager2.ORIENTATION_HORIZONTAL

//viewpager2设置适配器,接收一个RecyclerView.Adapter
viewPager2.adapter = MyTabAdapter(this, getFragmentList(titles))

//viewpager2关联tablayout
TabLayoutMediator(
  tabLayout,
  viewPager2,
  false,
  object : TabLayoutMediator.TabConfigurationStrategy {
    override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
      //必须设置tab的文字,否则无法显示tab的文字
      tab.text = titles[position]
    }
  }).attach()

//监听viewpager2的滑动事件
viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
  override fun onPageScrolled(
    position: Int,
    positionOffset: Float,
    positionOffsetPixels: Int
  ) {
    super.onPageScrolled(position, positionOffset, positionOffsetPixels)
    //滑动中
  }

  override fun onPageSelected(position: Int) {
    super.onPageSelected(position)
    //滑动完成
  }

  override fun onPageScrollStateChanged(state: Int) {
    super.onPageScrollStateChanged(state)
    //滑动状态的改变
  }
})


class MyTabAdapter(fragmentActivity: FragmentActivity,private val fragments:List<Fragment>) : FragmentStateAdapter(fragmentActivity) {
    override fun getItemCount(): Int {
        return fragments.size;
    }

    override fun createFragment(position: Int): Fragment {
        return fragments[position]
    }
}
 类似资料: