简体   繁体   中英

ConstraintLayout view binding migration from Kotlin synthetics

I have an existing view that extends from ConstraintLayout which looks something like this:

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
    }
}

I'm familiar with view binding with activities and fragments, but I can't find any documentation around the extends layout case. My question is, what do I replace that initial inflate call with here?

I'm assuming you have a context available from your constructor and your XML layout's top level tag is <merge> . You can use your binding class's inflate to create and add the child layout.

And since this can all be set up in the constructor, you don't need lateinit var like in the Activity/Fragment examples, and can just use val instead.

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
        }
    }
}

you can get layout inflater like below

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

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

and you must have valid view construct too

 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

for more information check

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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