【发布时间】:2022-04-24 16:54:16
【问题描述】:
我为我的选项卡布局制作了一个自定义选项卡项,并使用视图绑定对其进行了如下初始化:
val tabView = CustomTabBinding.inflate(LayoutInflater.from(mContext), null, false)
tabView.tvCustomTabTitle.text = it.title
tabView.tvCustomTabCount.visibility = View.GONE
现在,当用户选择/取消选择选项卡时,我想更改此自定义视图的外观。通常我使用 kotlin 合成来实现这一点,如下所示:
fun setOnSelectView(tabLayout: TabLayout, position: Int = 0) {
val tab = tabLayout.getTabAt(position)
val selected = tab?.customView
if (selected != null)
selected.tv_custom_tab_title?.apply {
setTextColor(mContext.getColorCompat(R.color.colorAccent))
typeface = setFont(true)
}
selected?.tv_custom_tab_count?.apply {
setBackgroundResource(R.drawable.bullet_accent)
mContext.getColorCompat(android.R.color.white)
}
}
但是现在我该如何使用视图绑定来实现呢?
我使用的是findViewById()的方法:
fun Context.setOnSelectView(tabLayout: TabLayout, position: Int = 0) {
val tab = tabLayout.getTabAt(position)
val selected = tab?.customView
if (selected != null){
val title = selected.findViewById<TextView>(R.id.tv_custom_tab_title)
val count = selected.findViewById<TextView>(R.id.tv_custom_tab_count)
title.apply {
setTextColor(getColorCompat(R.color.colorAccent))
typeface = setFont(true)
}
count.apply {
setBackgroundResource(R.drawable.bullet_accent)
getColorCompat(android.R.color.white)
}
}
}
但我希望有更好的方法来做到这一点。如果是,请帮帮我。
【问题讨论】:
标签: android android-view android-tablayout android-viewbinding