2

所以我试图在我的代码中访问 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){


}

4

3 回答 3

6

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

 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())
于 2018-10-19T06:04:06.257 回答
1

您不需要通过构造函数传递它。在 onCreateViewHolder 中,您可以从parent.context中获取它

于 2019-09-30T14:13:12.297 回答
-1

您可以使用 ContextCompat。

ContextCompat.getColor(this.applicationContext, android.R.color.transparent)
于 2020-09-08T09:35:19.943 回答