【问题标题】:ViewBinding abstract class or interfaceViewBinding 抽象类或接口
【发布时间】:2021-03-29 10:47:20
【问题描述】:

有没有办法为 ViewBinding 创建一个抽象类或接口。也许我会举一个简单的例子来说明我的意思。

假设我有两个片段。两者都有TextView 命名为universalTextView。在片段类中,我有值someText = "Text"。我想将此值设置为universalTextView。现在在两个片段中,我有相同的代码,所以我创建了一个抽象类,以减少样板代码,它包含someText 并为universalTextView 设置文本。它看起来像这样:

abstract class AbstractFragment(
    @LayoutRes layout: Int
) : Fragment(layout)
{
    protected abstract val binding: ViewBinding
    protected val someText = "Text"

    override fun onViewCreated(view: View, savedInstanceState: Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)
        binding.root.findViewById<TextView>(R.id.universalTextView).text = someText
    }
}

但是使用这种方法,我失去了 ViewBinding 的最大优势,我必须使用findViewById。有没有办法为 ViewBinding 创建一个抽象类,像这样:

abstract class AbstractViewBinding : ViewBinding
{
    abstract val universalTextView : TextView
}

所以在AbstractFragment 中,我可以使用protected abstract val binding: AbstractViewBinding 并在不使用findViewById 的情况下更改文本。但是现在,我必须以某种方式告诉应用程序,在扩展 AbstractFragment 的每个片段中使用的 ViewBinding 将具有 universalTextView。这甚至可能吗?

【问题讨论】:

  • @MartinMarconcini 这个 TextView 只是我想要实现的最简单的示例,因此每个人都可以轻松理解这一点。如果只有这 2 个 TextView,其中的值静态设置为 Text,我永远不会问这个问题:D
  • 啊好吧 :) 我有点担心。 (你得原谅我,有时我读到的问题与此有关)。
  • 无论如何,我不确定您是否可以这样做。您将需要一个“层”,从通用“T.setThisText”到“binding1.setThisText”和“binding2.setThisText”,此时您只是引入了更多复杂性,但当然,还有您想要抽象其中一些具有相似布局的东西的正当理由。
  • 我只是不认为你可以用 ViewBinding 做到这一点,因为它被设计成“类型安全”之类的,所以......没有考虑到“通用”的东西。
  • 好的,非常感谢。我认为不可能以我想做的方式去做。这也不是我必须做的事情,即使使用findViewById 也不是很糟糕,但我只是好奇是否有任何抽象 ViewBinding 模式

标签: android kotlin android-viewbinding


【解决方案1】:

我不认为这是直接可能的,在视图绑定中没有任何继承机制。相反,你可以有这样的结构:

abstract class AbstractFragment : Fragment {

    abstract val universalTextView: TextView
    protected val someText = "Text"

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        super.onViewCreated(view, savedInstanceState)
        universalTextView.text = someText
    }
}
class Fragment1 : AbstractFragment {
  
    lateinit var binding: Fragment1Binding
    override val universalTextView
        get() = binding.utv
}

但我知道这不是你想要的。

【讨论】:

  • 谢谢,这会有所帮助,但它也可以在更复杂的示例中生成大量样板代码。因为在每个片段中我都必须以相同的方式覆盖相同的字段
  • 是的,如果可能,请避免使用“基本片段”,而是更愿意将您需要的行为组合到可注入组件中,然后您可以从片段中调用(或已被生命周期观察者自动调用)
猜你喜欢
  • 1970-01-01
  • 2012-11-06
  • 2022-01-18
  • 2011-01-09
  • 2012-08-07
  • 2011-04-13
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
相关资源
最近更新 更多