我的TabLayout
遇到问题。我为我的标签创建了一个自定义视图,其中包括一个TextView
和一个ImageView
,并且上面有一个TabLayout.OnTabSelectedListener
。
我在TextView
方法上更改my onTabSelected
的字体的问题,但是每次我运行代码时,它似乎都为空。一旦我移到其他选项卡,它就可以正常工作!你能帮我理解这个问题吗?
我认为在设置选项卡自定义视图,适配器和侦听器之间存在时间问题。这是我的代码:
private val root: ViewGroup = parent.inflate(R.layout.container)
private val tabs by lazy { root.tab_layout }
private val pager by lazy { root.view_pager }
private val component1: Component1 by lazy {Component1()}
private val component2: Component2 by lazy {Component2()}
override fun onAttach() {
val tabList: List<Component> = listOf(
component1,
component2
)
tabs.setSelectedTabIndicatorColor(ContextCompat.getColor(view.context,R.color.grey))
tabs.setupWithViewPager(pager)
tabs.addOnTabSelectedListener(tabSelectedListener)
pager.adapter = ScreenAdapter(tabList)
setupCustomTabs(tabList)
}
override fun onDetach() {
tabs.clearOnTabSelectedListeners()
tabs.removeAllTabs()
}
private fun setupCustomTabs(tabList: List<Component>) {
for (i in tabList.indices) {
val customTab = LayoutInflater.from(root.context).inflate(R.layout.component_tab, null)
customTab.tab_text.text = tabList[i].title
customTab.tab_icon.setImageDrawable(tabList[i].icon)
tabs.getTabAt(i)?.customView = customTab
}
}
private val tabSelectedListener: TabLayout.OnTabSelectedListener = object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab?) {}
override fun onTabUnselected(tab: TabLayout.Tab?) {
if (tab != null){
val tabTextView = tab.customView?.tab_text
tabTextView?.setTextColor(ContextCompat.getColor(view.context,R.color.grey_9999AB))
tabTextView?.setTypeface(null, Typeface.NORMAL)
}
}
override fun onTabSelected(tab: TabLayout.Tab?) {
if (tab != null) {
val tabTextView = tab.customView?.tab_text
tabTextView?.setTextColor(ContextCompat.getColor(view.context,R.color.grey))
tabTextView?.tab_text?.setTypeface(tabTextView.typeface, Typeface.BOLD)
}
}
}
class ScreenAdapter<T>(private val tabs: List<T>) : PagerAdapter() {
override fun instantiateItem(container: ViewGroup, position: Int): Any = run {
val vc = tabs[position]
container.attach(vc)
return vc.view
}
override fun destroyItem(container: ViewGroup, position: Int, obj: Any) = container.detach(tabs[position])
override fun getPageTitle(position: Int): CharSequence? = null
override fun isViewFromObject(view: View, obj: Any): Boolean = view == obj
override fun getCount(): Int = tabs.size
}