繁体   English   中英

从 Kotlin 合成迁移 ConstraintLayout 视图绑定

[英]ConstraintLayout view binding migration from Kotlin synthetics

我有一个从ConstraintLayout扩展的现有视图,它看起来像这样:

class LandingTemplate: ConstraintLayout {

  init {
    inflate(context, R.layout.landing_template, this)
    
    // Currently this 'recyclerView' is a kotlin synthetic
    recyclerView.run {
      // this sets up the recycler view
    }
}

我熟悉带有活动和片段的视图绑定,但我找不到关于扩展布局案例的任何文档。 我的问题是,我用什么来代替最初的inflate调用?

我假设您的构造函数提供了一个上下文,并且您的 XML 布局的顶级标记是<merge> 您可以使用绑定类的inflate来创建和添加子布局。

由于这一切都可以在构造函数中进行设置,因此您不需要像 Activity/Fragment 示例中那样的lateinit var ,而可以使用val代替。

class LandingTemplate(context: Context, attrs: AttributeSet): ConstraintLayout(context, attrs) {

    private val binding = LandingTemplateBinding.inflate(LayoutInflater.from(context), this)

    init {
        binding.recyclerView.run {
            // this sets up the recycler view
        }
    }
}

你可以得到像下面这样的布局充气器

 val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

 val view = inflater.inflate(R.layout.landing_temple,this,true)

并且您也必须具有有效的视图构造

 LandingTemple(Context) // for creating view programmatically

 LandingTemple(Context,AttrributeSet) // to inflate view from xml , and 
 //the constructor context is one that you use to call `getSystemService

欲了解更多信息, 请检查

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM