我在选项卡布局中使用了自定义视图。
<com.google.android.material.tabs.TabLayout
android:id="@+id/mainTabBar"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimaryDark"
app:tabGravity="fill"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/colorPrimary" />
var mainPagerAdapter = MainPagerAdapter(supportFragmentManager!!)
viewPager.setAdapter(mainPagerAdapter)
viewPager.setOffscreenPageLimit(mainPagerAdapter.getCount())
for (i in 0 until mainPagerAdapter.getCount()) {
val tab = mainTabBar.newTab()
val tabView = mainPagerAdapter.getTabView(i, this)
tab.setCustomView(tabView)
mainTabBar.addTab(tab)
}
val tab = mainTabBar.getTabAt(0)
if (tab != null) {
tab.select()
val view = tab.customView
mainPagerAdapter.changeColorOfTabView(view!!, true, this,tab.position)
}
viewPager.setCurrentItem(0)
mainTabBar.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
viewPager.currentItem = tab.getPosition()
val view = tab.getCustomView()
mainPagerAdapter.changeColorOfTabView(view!!, true, this@MainActivity, tab.position)
}
override fun onTabUnselected(tab: TabLayout.Tab) {
val view = tab.getCustomView()
mainPagerAdapter.changeColorOfTabView(view!!, false, this@MainActivity, tab.position)
}
override fun onTabReselected(tab: TabLayout.Tab) {}
})
fun getTabView(i: Int, context: Context): View {
val tabView = LayoutInflater.from(context).inflate(R.layout.tab_main, null) as LinearLayout
val text = tabView.findViewById<TextView>(R.id.tabTextView)
val icon = tabView.findViewById<ImageView>(R.id.drawableTop)
text.setText(getPageTitle(i))
text.setTextColor(context.getResources().getColor(R.color.white))
icon.setImageResource(getIconResId(i))
if (i == 3) {
tabView.isSelected = true
}
return tabView
}
tab_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="10dp"
android:orientation="vertical">
<ImageView
android:id="@+id/drawableTop"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true" />
<TextView
android:id="@+id/tabTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/drawableTop"
android:layout_centerHorizontal="true"
android:textColor="@color/toggle_text_color_gray_red"
android:textSize="11sp" />
</LinearLayout>