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?
Kotlin Android Extensions is deprecated, which means that using Kotlin synthetics for view binding is no longer supported.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With