所以我试图在我的代码中访问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){
}
答案 0 :(得分:1)
在您的适配器中将上下文作为参数传递,然后像这样使用
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())
答案 1 :(得分:0)
您不需要通过构造函数传递它。 在onCreateViewHolder中,您可以从 parent.context
答案 2 :(得分:-1)
您可以使用ContextCompat。
ContextCompat.getColor(this.applicationContext, android.R.color.transparent)