Kotlin synthetic in Adapter or ViewHolder

前端 未结 7 657
孤独总比滥情好
孤独总比滥情好 2020-12-13 05:36

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 \

7条回答
  •  清歌不尽
    2020-12-13 06:06

    Simple example from https://github.com/antoniolg/Kotlin-for-Android-Developers

    import kotlinx.android.synthetic.item_forecast.view.*
    
    class ForecastListAdapter() : RecyclerView.Adapter() {
    
        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!

提交回复
热议问题