【发布时间】:2022-10-18 15:38:05
【问题描述】:
标签: java android android-viewpager android-tablayout
标签: java android android-viewpager android-tablayout
第一次启动tabLayout。
val tabLayoutMediator = TabLayoutMediator(
binding.filterNotes.tabLayout, binding.filterNotes.viewPager
) { tab, position ->
val v = LayoutInflater.from(requireActivity())
.inflate(R.layout.custom_tab_adapter, null, false)
val tv = v.findViewById<TextView>(R.id.text_custom_adapter)
if (position == 0) {
tv?.background =
ContextCompat.getDrawable(requireContext(), R.drawable.background_accent_orange)
tv.setTextColor(ContextCompat.getColor(tv.context, R.color.lightTextColor))
} else {
tv.background =
ContextCompat.getDrawable(requireContext(), R.drawable.background8dp_solid_white)
tv.setTextColor(ContextCompat.getColor(tv.context, R.color.lightTextSecondary))
}
tv.text = tabNameList[position]
tab.customView = v
}
tabLayoutMediator.attach()
之后,当您单击任何选项卡布局项时
binding.filterNotes.tabLayout.addOnTabSelectedListener(object :
TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
val selected = tab.customView
if (selected != null) {
val ivText = selected.findViewById<TextView>
(R.id.text_custom_adapter)
ivText?.background =
ContextCompat.getDrawable(requireContext(),
R.drawable.background_accent_orange)
ivText.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.lightTextColor
)
)
}
}
override fun onTabUnselected(tab: TabLayout.Tab) {
val selected = tab.customView
if (selected != null) {
val ivText = selected.findViewById<TextView>
(R.id.text_custom_adapter)
ivText?.background =
ContextCompat.getDrawable(requireContext(),
R.drawable.background8dp_solid_white)
ivText.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.lightTextSecondary
)
)
}
}
override fun onTabReselected(tab: TabLayout.Tab) {}
})
custum_tab_adapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/_10dp">
<LinearLayout
android:id="@+id/linear_custom_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/text_custom_adapter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/avertastd_semibold"
android:gravity="center"
android:lineHeight="@dimen/_18dp"
android:paddingStart="@dimen/_10dp"
android:paddingTop="@dimen/_12dp"
android:paddingEnd="@dimen/_10dp"
android:paddingBottom="@dimen/_8dp"
android:textColor="@color/lightTextSecondary"
android:textSize="@dimen/_14sp" />
</LinearLayout>
【讨论】: