Adapter 或 ViewHolder 中的 Kotlin 合成 [英] Kotlin synthetic in Adapter or ViewHolder
本文介绍了Adapter 或 ViewHolder 中的 Kotlin 合成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 kotlin 新手.我发现并尝试在我的 Activity
类中使用合成方法而不是烦人的方法 findViewById
,但我发现如果我们想调用 View 上的合成属性(有用在适配器类中),我们还应该导入 kotlinx.android.synthetic.main.view.*."但我无法弄清楚它究竟是如何工作的?有例子吗?
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?
推荐答案
来自 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()
}
}
}
不用写
val view = itemView.findViewById(R.id.date) as TextView
view.text = forecast.date.toDateString()
就
itemView.date.text = forecast.date.toDateString()
简单有效!
这篇关于Adapter 或 ViewHolder 中的 Kotlin 合成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文