Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin synthetic in Adapter or ViewHolder

I am new in kotlin. I have found and tried to use synthetic method instead of annoying method findViewById in my Activity class, but I have found "If we want to call the synthetic properties on View (useful in adapter classes), we should also import kotlinx.android.synthetic.main.view.*." But I can't figure out how it exactly works? Is there any examples?

like image 606
busylee Avatar asked Oct 23 '15 14:10

busylee


People also ask

Is kotlin synthetic deprecated?

Kotlin Android Extensions is deprecated, which means that using Kotlin synthetics for view binding is no longer supported.

What is ViewHolder in Kotlin?

ViewHolder for each Item in the List. PreferenceViewHolder. A RecyclerView. ViewHolder class which caches views associated with the default Preference layouts. A ViewHolder describes an item view and metadata about its place within the RecyclerView.

How does kotlin synthetic work?

For every layout file, Kotlin Synthetics creates an autogenerated class containing your view— as simple as that. You just have to import this plugin in your Gradle file, and you are all set to directly refer to the view reference variables. It calls findViewById internally only once and then caches it.

What is a ViewHolder Android?

A ViewHolder describes an item view and metadata about its place within the RecyclerView. RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive View. findViewById(int) results.


1 Answers

Simple example from https://github.com/antoniolg/Kotlin-for-Android-Developers

import kotlinx.android.synthetic.item_forecast.view.*  class ForecastListAdapter() : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {      class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {          fun bindForecast(forecast: Forecast) {             itemView.date.text = forecast.date.toDateString()         }     } } 

No need to write

val view = itemView.findViewById(R.id.date) as TextView view.text = forecast.date.toDateString() 

Just

itemView.date.text = forecast.date.toDateString() 

Simple and effective!

like image 96
Peter Zhao Avatar answered Sep 20 '22 19:09

Peter Zhao