使Forecast list可点击
Domain model和数据映射时必须生成完整的图标uil,所以我们可以这样去加载它:
data class Forecast(val date: String, val description: String,
val high: Int, val low: Int, val iconUrl: String)
在ForecastDataMapper
中:
private fun convertForecastItemToDomain(forecast: Forecast): ModelForecast {
return ModelForecast(convertDate(forecast.dt),
forecast.weather[0].description, forecast.temp.max.toInt(),
forecast.temp.min.toInt(), generateIconUrl(forecast.weather[0].icon))
}
private fun generateIconUrl(iconCode: String): String
= "http://openweathermap.org/img/w/$iconCode.png"
我们从第一个请求中得到图标的code,用来组成完成的图标url。加载图片最简单的方式是使用图片加载库。是一个不错的选择。它需要加到build.gradle
的依赖中:
}
如果你还记得上一课程,当被调用时invoke
方法可以被省略。所以我们来使用它来简化。listener可以被以下两种方式调用:
itemClick.invoke(forecast)
itemClick(forecast)
ViewHolder
将负责去绑定数据到新的View:
现在Adapter的构造方法接收一个itemClick
。创建和绑定数据也是更简单:
public class ForecastListAdapter(val weekForecast: ForecastList,
val itemClick: ForecastListAdapter.OnItemClickListener) :
RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
ViewHolder {
.inflate(R.layout.item_forecast, parent, false)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindForecast(weekForecast[position])
}
...
}
val View.ctx: Context
从现在开始,任何View都可以使用这个属性了。这个不是必须的,因为你可以使用扩展的context属性,但是我觉得如果我们使用的话在其它类中也会更有连贯性。而且,这是一个很好的怎么去使用扩展属性的例子。
最后,MainActivity调用setAdapter,最后结果是这样的:
如你所见,创建一个匿名内部类,我们去创建了一个实现了刚刚创建的接口的对象。看起来不是很好,对吧?这是因为我们还没开始试使用另一个强大的函数式编程的特性,但是你将会在下一章中学习到怎么去把这些代码转换得更简单。