未解决的引用getResources() Kotlin

3

我正在尝试在代码中访问getResources(),但由于某些原因它始终无法解决引用。 我正在为我的数组适配器的另一个类中进行此操作。这是因为我没有主方法还是因为其他原因? 我有点新手在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){


}


在这种情况下,您需要使用上下文来正确引用,例如viewHolder.itemView.context.resources。在您的情况下,是p0.itemView.context.resources - Hanzala
[this.]getResources() 是一个方法,当你扩展一个作为 Context 的类时存在,例如 Activity 或者内部有一个引用的 ViewRecyclerView.Adapter 没有继承这个方法,所以你需要一个外部 Context 对象的引用。可以像上面的评论建议那样,在构造函数中要求显式引用,或者使用作为方法参数给出的 View 对象。 - zapl
3个回答

8

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

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

好的,那么在调用类时我会像这样传递它吗? view.adapter = ForecastAdapter(weather, context) 当我这样传递它时,它会显示未解决的引用。 - Zubair Amjad
1
当您在Activity中执行@ZubairAmjad view.adapter = ForecastAdapter(weather, this)时,或者如果您是从Fragment中执行,则为view.adapter = ForecastAdapter(weather, activity!!)getActivity())。 - zapl
当我这样做时,它说它想要上下文,但我认为这将指向上下文? - Zubair Amjad

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

-1

您可以使用ContextCompat。

ContextCompat.getColor(this.applicationContext, android.R.color.transparent)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接