Kotlin synthetic in Adapter or ViewHolder

2019-01-22 01:32发布

问题:

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?

回答1:

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!



回答2:

Kotling 1.1.4 out

Further information : https://antonioleiva.com/kotlin-android-extensions/

So you need to enable them adding this to you build.gradle:

apply plugin: 'org.jetbrains.kotlin.android.extensions'
androidExtensions {
    experimental = true
}

Since this new version of Kotlin, the Android Extensions have incorporated some new interesting features: caches in any class (which interestingly includes ViewHolder)

Using it on a ViewHolder (or any custom class)

class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), 
        LayoutContainer {

    fun bind(title: String) {
        itemTitle.text = "Hello Kotlin!"
    }
}


回答3:

You need

import kotlinx.android.synthetic.row_wall.view.*

And later something along the lines of:

convertView.titleText.text = item.title

The point is that the view.* introduces extensions to the View class.



回答4:

Try

class CustomViewModel(val baseView: View) { val firstName = baseView.firstName val lastName = baseView.lastName }

View object exposes the views ref:https://discuss.kotlinlang.org/t/unable-to-use-kotlin-android-extension-in-adapter-class/2890



回答5:

It means you have to place this line at the beginning of your source file:

import kotlinx.android.synthetic.main.view.*

So now instead of, for example, findView(R.id.textView) as TextView you would write just textView. The latter is a synthetic extension property located in the package kotlinx.android.synthetic.main.view, that's why you have to import everything from it.

There's a tutorial on the official site, take a look.