【问题标题】:How to reverse View Binding from custom tab layout in Android?如何从 Android 中的自定义选项卡布局反转视图绑定?
【发布时间】: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


    【解决方案1】:

    回复晚了,但这是我将视图绑定用于自定义选项卡布局的方式,希望对您有所帮助

    custom_tab.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    
      <TextView
        android:id="@+id/tv_custom_tab_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
      <TextView
        android:id="@+id/tv_custom_tab_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
    </LinearLayout>
    

    您的活动/片段:

    val tab = binding.tabLayout.getTabAt(position)
    tab.setCustomView(R.layout.custom_tab)
    val tabBinding = tab.customView?.let {
            CustomTabBinding.bind(it)
        }
    tabBinding?.tvCustomTabTitle?.text = "your title here"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多