有没有办法为ViewBinding创建一个抽象的类或接口?也许我会举一个简单的例子来说明我真正的意思。
假设我有两个片段。两者都有名为universalTextView的TextView。在片段类中,我的值是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。这有可能吗?
发布于 2021-03-29 20:11:28
我不认为这是直接可能的,视图绑定中没有任何类型的继承机制。取而代之的是,你可以有这样的结构:
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
}但我意识到这并不是你想要的。
https://stackoverflow.com/questions/66852816
复制相似问题