简体   繁体   中英

How to convert Kotlin synthetics to view binding for inflated XML in a loop?

While trying to convert an application from the defunct Kotlin synthetics to the newer/supported view binding method, I ran into this issue where layouts are being inflated in a loop and attached to the target parent view:

for (item in itemList) {
  val view = LayoutInflater.from(this).inflate(R.layout.imageitem_row, binding.linear, false)
  view.text1.text = item.title
  view.text2.text = item.pubdate
  binding.linear.addView(view)
}

Since Kotlin synthetics are being removed from the code, text1 and text2 are not valid properties of view . So how do I apply view binding to this inflated layout? Or does that not work here and I should be using findViewById() instead for text1 and text2 ?

Just to explain what's going on - with the synthetics library, it was basically doing view binding in the activity itself (or whatever). For each view with an id in your layout, it was adding a property you could access directly. So you could just call text1.text in the current scope, and that would have been automatically bound to a view in the hierarchy.

With view binding, there's no magic and no throwing properties into that top-level scope. Instead, each layout has an automatically generated class with Binding added to the end of the name, like ImageItemRowBinding . This class has a property for each view with an id, so it's all encapsulated in one place.

You either call bind(view) on it to get an instance with all the properties assigned (by finding them in the view hierarchy you pass in), or you can call inflate if you don't have the view yet, and you want it to inflate that while it's binding. You end up getting back an instance of the binding class with all the view properties assigned (and you can access the top of the view hierarchy through the root property).

Aside from that, it's basically the same! You just have to manually create your binding instances, and access your views through that. Don't forget you can use Kotlin functions like with(binding) or binding.run { } to work with its properties without needing the binding prefix every time, so you can pretty much just wrap your original synthetics-based code if it's convenient

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