首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ViewBinding抽象类或接口

ViewBinding抽象类或接口
EN

Stack Overflow用户
提问于 2021-03-29 18:47:21
回答 1查看 179关注 0票数 1

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

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

代码语言:javascript
复制
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创建一个抽象类,就像这样:

代码语言:javascript
复制
abstract class AbstractViewBinding : ViewBinding
{
    abstract val universalTextView : TextView
}

因此,在AbstractFragment中,我可以使用protected abstract val binding: AbstractViewBinding而不使用findViewById来更改文本。但现在,不知何故,我必须告诉应用程序,在扩展AbstractFragment的每个片段中使用的ViewBinding都将具有universalTextView。这有可能吗?

EN

回答 1

Stack Overflow用户

发布于 2021-03-29 20:11:28

我不认为这是直接可能的,视图绑定中没有任何类型的继承机制。取而代之的是,你可以有这样的结构:

代码语言:javascript
复制
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
    }
}
代码语言:javascript
复制
class Fragment1 : AbstractFragment {
  
    lateinit var binding: Fragment1Binding
    override val universalTextView
        get() = binding.utv
}

但我意识到这并不是你想要的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66852816

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档