gpt4 book ai didi

适配器或 ViewHolder 中的 Kotlin 合成

转载 作者:IT老高 更新时间:2023-10-28 13:26:13 26 4
gpt4 key购买 nike

我是 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()

简单有效!

关于适配器或 ViewHolder 中的 Kotlin 合成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33304570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com