未解决的参考 getResources() Kotlin
Unresolved Reference getResources() Kotlin
所以我试图在我的代码中访问 getResources(),但由于某种原因,它一直在获取未解析的引用。我正在为我的阵列适配器在另一个 class 中执行此操作。是我没有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())
您不需要通过构造函数传递它。
在 onCreateViewHolder 你可以从 parent.context
您可以使用 ContextCompat。
ContextCompat.getColor(this.applicationContext, android.R.color.transparent)
所以我试图在我的代码中访问 getResources(),但由于某种原因,它一直在获取未解析的引用。我正在为我的阵列适配器在另一个 class 中执行此操作。是我没有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())
您不需要通过构造函数传递它。 在 onCreateViewHolder 你可以从 parent.context
您可以使用 ContextCompat。
ContextCompat.getColor(this.applicationContext, android.R.color.transparent)