首页 > 解决方案 > 未解决的参考 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){


}

标签: androidkotlinandroid-arrayadaptercustom-arrayadapter

解决方案


将上下文作为参数传递给适配器,然后像这样使用

 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())

推荐阅读