【问题标题】:ConstraintLayout view binding migration from Kotlin synthetics从 Kotlin 合成的 ConstraintLayout 视图绑定迁移
【发布时间】:2021-07-19 23:10:49
【问题描述】:

我有一个从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 调用?

【问题讨论】:

    标签: android kotlin android-viewbinding


    【解决方案1】:

    我假设您的构造函数提供了一个上下文,并且您的 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
            }
        }
    }
    

    【讨论】:

    • 是的,顶层是<merge>,这对我有用。谢谢!
    【解决方案2】:

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

     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
    

    更多信息check

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2017-12-05
      相关资源
      最近更新 更多