5.0 操作符重载

2018-08-29  本文已影响0人  kavenka

简化前面的的天气列表的例子,在ForecastList.kt这个类中,实现一个get方法,还有一个size方法:

data class ForecastList(val city: String, val country: String, val dailyForecast: List<com.kavenka.testkotlin.domain.Forecast>) {
    operator fun get(position: Int): Forecast = dailyForecast[position]
    fun size(): Int = dailyForecast.size
}

然后在我们的adapter类中,我们可以写得更简单一点

class ForecastListAdapter(val weekForecast: ForecastList) : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(TextView(parent.getContext()))
    }
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//        with(weekForecast.dailyForecast[position]) {
//            holder.textView.text = "$date - $description - $high/$low"
//        }
        with(weekForecast[position]) {
            holder.textView.text = "$date - $description - $high/$low"
        }
    }
//    override fun getItemCount(): Int = weekForecast.dailyForecast.size
    override fun getItemCount(): Int = weekForecast.size()
    class ViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)
}

将dailyForecast的每一项对应的赋值给ForecastList,在外部访问ForecastList的item时,实际获取的是dailyForecast的item。size方法也是一样。

扩展函数的操作符

定义ViewGroup的扩展函数get,使其可以直接访问ViewGroup中的子view

operator fun ViewGroup.get(position: Int): View = getChildAt(position)

现在真的可以非常简单地从一个 ViewGroup 中通过position得到一个view

val container: ViewGroup = find(R.id.container)
val view = container[2]
上一篇下一篇

猜你喜欢

热点阅读