适配器或ViewHolder中的Kotlin综合

我是kotlin的新手。 我发现并尝试使用合成方法,而不是在我的Activity类中使用烦人的方法findViewById ,但是我发现“如果我们想调用View上的综合属性(在适配器类中有用),我们还应该导入kotlinx.android.synthetic .main.view。*“。 但我不明白它是如何工作的? 有没有例子?

来自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() 

简单而有效!

科特林1.1.4了

更多信息: https : //antonioleiva.com/kotlin-android-extensions/

所以你需要启用他们添加到你build.gradle:

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

从Kotlin的这个新版本开始,Android扩展包含了一些新的有趣功能:任何类的缓存(有趣的是包括ViewHolder)

在ViewHolder(或任何自定义类)上使用它,

 class ViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun bind(title: String) { itemTitle.text = "Hello Kotlin!" } } 

你需要

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

后来的事情是:

 convertView.titleText.text = item.title 

关键是view。*引入了View类的扩展。

这意味着你必须把这行放在源文件的开头:

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

所以,现在,而不是,例如, findView(R.id.textView) as TextView你只需要编写textView 。 后者是位于包kotlinx.android.synthetic.main.view的合成扩展属性,这就是为什么您必须从中导入所有内容。

在官方网站有一个教程 ,看看。