Kotlin合成在Adapter或ViewHolder中 [英] Kotlin synthetic in Adapter or ViewHolder

查看:321
本文介绍了Kotlin合成在Adapter或ViewHolder中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是科特林的新人.我已经发现并尝试在我的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()

简单有效!

这篇关于Kotlin合成在Adapter或ViewHolder中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆