android - 未解决的参考 getResources() Kotlin
问题描述
所以我试图在我的代码中访问 getResources(),但由于某种原因,它不断得到一个未解决的引用。我正在另一个类中为我的数组适配器执行此操作。是因为我没有 main 方法还是因为其他原因?一般来说,我对 android dev 和 kotlin 有点陌生,所以任何帮助都将不胜感激。
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 drawableId: Int = getResources().getIdentifier("my_drawable", "drawable", getPackageName())
val getWeather = forecast.list[p1]
val clouds = getWeather.weather[0]
val getDateTime = forecast.list[p1]
var getIcon = forecast.list[p1]
var icon = getIcon.weather[0]
p0.view.textView_text_clouds.text = clouds.main
p0.view.textView_date_time.text = getDateTime.dt_txt
}
}
class ForecastData(val view: View): RecyclerView.ViewHolder(view){
}
解决方案
将上下文作为参数传递给适配器,然后像这样使用
class ForecastAdapter(val forecast: Forecast,val context:Context)
然后
override fun onBindViewHolder(p0: ForecastData, p1: Int) {
val drawableId: Int = context.getResources().getIdentifier("my_drawable", "drawable", getPackageName())
推荐阅读
- xamarin - 如何从 Xamarin 中的 ViewModel 获取数据
- javascript - 如果我已经定义了 div,定义了它的类、id 等,我可以稍后(以某种方式)添加 onclick="myFunction()" 吗?
- python-3.x - /save_data/ 处的 ValueError
- ios - MessageKit 中的 messageCollectionView 无法识别
- python - Python默认参数分配列表的长度
- heroku - 部署了heroku应用程序,但是当我尝试访问该应用程序时,当我使用heroku日志时出现以下错误--tail
- javascript - 刚才在 VueJS 和 Laravel
- tensorflow - 在线训练有状态的深度 LSTM 堆栈时出错
- javascript - 是否可以触发注入