您可以使用TabLayout.getTab(position) 来获取已选择的选项卡和未选择的选项卡。一旦你有了Tab 实例,你就可以调用Tab.setText("") 这应该会删除标签的标题。
val titles = listOf("tab1", "tab2", "tab3")
val tabs = titles.map {
tabLayout.newTab().also {
tabLayout.addTab(it)
it.setIcon(R.mipmap.ic_launcher)
}
}
tabLayout.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab?) {
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
tab?.text = ""
}
override fun onTabSelected(tab: TabLayout.Tab?) {
val index = tabs.indexOfFirst { it == tab }
tab?.text = titles[index]
}
})
更新
您可以通过为您的 Tab 使用自定义视图来实现该效果。
1 为您的选项卡创建视图布局。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
tools:layout_height="48dp"
android:padding="4dp">
<ImageView
android:id="@+id/tab_icon"
android:layout_width="36dp"
android:layout_height="36dp"
tools:srcCompat="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/tab_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:textSize="18sp"
tools:text="Tab title"/>
</LinearLayout>
2 在您的 Tab 中使用自定义视图
val tabs = titles.map {
tabLayout.newTab().also {
tabLayout.addTab(it)
val tabView = LayoutInflater.from(this).inflate(R.layout.tab_item_layout, tabLayout, false)
tabView.findViewById<ImageView>(R.id.tab_icon).setImageResource(R.mipmap.ic_launcher)
tabView.findViewById<TextView>(R.id.tab_title).text = title
it.customView = tabView
}
}
3 选择选项卡时更新标题的可见性。
tabLayout.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab?) {
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
tab?.customView?.findViewById<TextView>(R.id.tab_title)?.apply {
visibility = View.GONE
}
}
override fun onTabSelected(tab: TabLayout.Tab?) {
tab?.customView?.findViewById<TextView>(R.id.tab_title)?.apply {
visibility = View.VISIBLE
}
}
})
4 在您用 XML 声明 TabLayout 时,您需要添加 app:tabMode="scrollable"