前言
TabLayout 是 Android Material Design 库中的一个 UI 控件,它提供了一种方式来组织和显示多个选项卡。这些选项卡通常用于在应用程序中切换不同的视图或内容区域。TabLayout 可以单独使用,但更常见的是与 ViewPager2 一起使用,以便用户可以通过滑动屏幕来浏览不同的页面。
使用基本步骤如下:
一、添加依赖
dependencies {
implementation 'com.google.android.material:material:版本号'
implementation 'androidx.viewpager2:viewpager2:版本号'
}
二、定义布局文件
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/sc_act_all_type_top"
layout="@layout/base_include_title" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/sc_act_tab_all"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/base_white"
app:tabGravity="fill"
app:tabRippleColor="@null"
app:tabMode="fixed"
app:tabPaddingEnd="-1dp"
app:tabPaddingStart="-1dp"
android:layout_marginEnd="@dimen/dp_3"
app:tabBackground="@android:color/transparent"
app:tabIndicatorFullWidth="false"
app:tabTextAppearance="@style/TextAppearance"
app:tabIndicator="@drawable/sc_all_types_indicator_shape"
app:layout_constraintTop_toBottomOf="@+id/sc_act_all_type_top"/>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/sc_act_vp_all"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@+id/sc_act_tab_all"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
下面是对TabLayout中某些属性的解释:
- app:tabGravity="fill": 使所有选项卡均匀填充整个 TabLayout 的宽度。
- app:tabRippleColor="@null": 取消选项卡被点击时的涟漪效果。
- app:tabMode="fixed": 固定模式下,所有选项卡都显示在一行中,如果超过屏幕宽度,则启用水平滚动。
- app:tabPaddingEnd="-1dp" 和 app:tabPaddingStart="-1dp": 减少选项卡之间的内边距,使得选项卡更紧密地排列在一起。
- android:layout_marginEnd="@dimen/dim_3": 设置 TabLayout 的右侧外边距。
- app:tabBackground="@android:color/transparent": 设置选项卡的背景为透明。
- app:tabIndicatorFullWidth="false": 使指示器只覆盖选中的选项卡文本部分,而不是整个选项卡。
- app:tabTextAppearance="@style/TextAppearance": 设置选项卡文字的样式。
- app:tabIndicator="@drawable/sc_all_types_indicator_shape": 设置选中选项卡下方的指示器形状。
三、创建适配器
需要创建一个继承自 FragmentStateAdapter 的类作为 ViewPager2 的适配器。这个适配器将管理每个标签页对应的 Fragment
class ScAllTypeToolsVpAdapter(manager: FragmentManager, val lifecycle: Lifecycle,
var tabList: List<ScTabDataBean> = mutableListOf(),
var scChildAll: Boolean = false) :
FragmentStateAdapter(manager, lifecycle) {
override fun getItemCount(): Int = tabList.size
override fun createFragment(position: Int): Fragment {
return ScToolsListFrag.getInstance(tabList[position], scChildAll)
}
}
因为需求实现的页面是同样的结构,ViewPager2 中的 Fragment 中只有一个RecycleView,所以在适配器中的 createFragment 方法中采用动态构建 Fragment 的方法——调用Fragment中的getInstance方法获取fragment实例(如下代码)
companion object {
private const val KEY_ARGUMENTS_SC_TAB_DATA_BEAN = "ScTabDataBean"
private const val KEY_ARGUMENTS_SC_CHILD_ALL = "scChildAll"
fun getInstance(scTabDataBean: ScTabDataBean, scChildAll: Boolean)
: ScToolsListFrag
{
val scToolsListFrag = ScToolsListFrag()
val bundle = Bundle()
bundle.putParcelable(KEY_ARGUMENTS_SC_TAB_DATA_BEAN, scTabDataBean)
bundle.putBoolean(KEY_ARGUMENTS_SC_CHILD_ALL, scChildAll)
scToolsListFrag.arguments = bundle
return scToolsListFrag
}
}
在 Android 开发中,arguments 是一个 Bundle 对象,它与 Fragment 相关联,用于在创建 Fragment 时传递数据。这个 Bundle 可以包含各种类型的数据,如字符串、整数、浮点数、布尔值和其他 Parcelable 或 Serializable 对象。arguments 在 Fragment 的生命周期中可以被访问,常用于初始化 Fragment 所需的数据。
四、关联 TabLayout 和 ViewPager2
TabLayoutMediator 是 Material Components 库中的一个类,用于将 TabLayout 与 ViewPager2 关联起来。它可以帮助你自动同步 TabLayout 和 ViewPager2 的状态,确保用户在点击选项卡或滑动页面时,两者能够保持一致。
详细了解可进官方文档:TabLayoutMediator官方文档
TabLayoutMediator(mDataBind.scActTabAll,mDataBind.scActVpAll, true,
true) { tab: TabLayout.Tab?, pos ->
tab?.run {
text = vpAdapter.tabList[pos].title
}
}.run {
attach()
}
1、初始化 TabLayoutMediator:
- 第一个参数 mDataBind.scActTabAll 是 TabLayout 实例。
- 第二个参数 mDataBind.scActVpAll 是 ViewPager 实例。
- 第三个参数 true 表示 TabLayoutMediator 将自动处理标签的选中状态,当 ViewPager 的页面改变时,相应的标签也会被设置为选中状态。
- 第四个参数 true 表示 TabLayoutMediator 将自动处理标签的容器点击事件,当用户点击标签时,ViewPager 将滚动到相应的页面。
2、设置标签选择监听器:
使用 lambda 表达式 { tab: TabLayout.Tab?, pos -> ... } 来为每个标签设置文本。 tab 是当前的 TabLayout.Tab 对象,pos 是当前标签在 TabLayout 中的位置。
3、设置标签文本:
text = vpAdapter.tabList[pos].title 设置了标签的文本,这个文本来自 vpAdapter.tabList 数组的 title 属性,pos 用于索引数组获取相应标签的标题。
4、附加到 TabLayout 和 ViewPager:
使用 run { attach() } 来调用 TabLayoutMediator 的 attach 方法,这会将 TabLayoutMediator 与 TabLayout 和 ViewPager 关联起来,确保它们的同步。
五、设置TabLayout 的点击处理
这段代码定义了一个 TabLayout.OnTabSelectedListener 匿名类的实例 tabSelectListener,用于监听 TabLayout 中标签的选择、取消选择和重新选择事件。
private val tabSelectListener = object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab?) {
tab?.customView = TextView(this@ScAllTypeToolsAct).apply {
// 设置文本颜色
setTextColor(getColorExt(R.color.base_dark_33))
// 设置文本居中
gravity = Gravity.CENTER
setSingleLine()
// 设置文本加粗
setMedium()
text = tab?.text
}
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
tab?.customView = null
}
override fun onTabReselected(tab: TabLayout.Tab?) {
}
}
设置完成之后如下设置使点击事件生效:
mDataBind.scActTabAll.addOnTabSelectedListener(tabSelectListener)