android - Android 自定义适配器越界异常
问题描述
在 Kotlin 中编写一个 android 应用程序时,我遇到了这个错误:
我正在使用OpenWeatherMapApi并尝试从 API 中获取预测数据。由于 okhttp3 和 Gson,我能够提取预测数据,但现在我的问题是显示该数据。我为自定义 ArrayAdapter 创建了一个新类,我尝试在我创建的 textView 中显示,但我完全不知道为什么我不断收到错误数组的大小不应该为 1 但它结束了拥有它
代码
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.weather_row.view.*
class ForecastAdapter(val forecast: Forecast) : RecyclerView.Adapter<ForecastData>(){
override fun getItemCount(): Int {
return forecast.list.count()
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ForecastData {
val layoutInflator = LayoutInflater.from(p0?.context)
val cellForRow = layoutInflator.inflate(R.layout.weather_row, p0, false)
return ForecastData(cellForRow)
}
override fun onBindViewHolder(p0: ForecastData, p1: Int) {
val getWeather = forecast.list[p1]
val clouds = getWeather.weather[p1]
p0.view.textView_text_clouds.text = clouds.main
}
}
class ForecastData(val view: View): RecyclerView.ViewHolder(view){
}
解决方案
你的问题是
getWeather.weather[p1]
“weather
列表”并不是真正的列表。它通常只有一个元素。
改用这个:
getWeather.weather[0]
推荐阅读
- google-chrome - 为什么即使存在缓存控制标头,Chrome 也不缓存响应?
- vue.js - 我可以使用 Vue.Draggable 从操作系统中拖动文件吗?
- javascript - 如何在一个数组中找到连续多少次相同的值?
- docker - Docker-Compose:cap_drop 和 cap_add 的顺序?
- r - 如何在 R 中以对数刻度 (y) 绘制数据
- python - 从源页面解析列表
- python - 熊猫 - 无法计算移动平均线
- java - Java中的super()方法
- json - 使用带有 jq 的正则表达式根据其他嵌套属性的值选择对象
- java - Android TextToSpeech 总是无法运行