所以我正在使用OpenWeatherMap Api创建一个阳光观察器应用程序,所以我现在遇到的问题是,我的可绘制文件夹中有所有图标,问题是我想显示所有图标,现在我已经这样设置了:
我正在使用该硬编码图标作为占位符,但我想显示所有其他图标,我的问题是如何做到这一点,来自api的图像以字符串格式给出,我不知道如何将从可绘制文件夹中获取它们
代码
// Array Adapter
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 getWeather = forecast.list[p1]
val clouds = getWeather.weather[0]
val getDateTime = forecast.list[p1]
val getIcon = forecast.list[p1]
// val icon = getIcon.weather[0]
p0.view.textView_text_clouds.text = clouds.main
p0.view.textView_date_time.text = getDateTime.dt_txt
// p0.view.imageView_icon = icon.icon
}
}
class ForecastData(val view: View): RecyclerView.ViewHolder(view){
}
// MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
searchButton.setOnClickListener {
getRequest()
}
view.layoutManager = LinearLayoutManager(this)
// val drawableId: Int = getResources().getIdentifier("drawable", "drawable", getPackageName())
}
private fun getRequest() {
val input = searchBar.getText().toString()
val url = "http://api.openweathermap.org/data/2.5/forecast?zip=" + input + "&units=imperial&APPID=" + getString(R.string.OPEN_WEATHER_MAP_API_KEY)
val request = okhttp3.Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call, response: okhttp3.Response) {
val body = response?.body()?.string()
println(body)
val gson = GsonBuilder().create()
val weather = gson.fromJson(body, Forecast::class.java)
runOnUiThread {
view.adapter = ForecastAdapter(weather)
}
}
override fun onFailure(call: Call, e: IOException) {
println("Failed to execute")
}
})
}
}
答案 0 :(得分:0)
使用时间
when(“ forecast.list [p1]”){ “ icon01d.png”-> p0.view.imageView_icon.setDrawable(R.drawable.icon01d.png)
“ icon02n.png”-> p0.view.imageView_icon.setDrawable(R.drawable.icon02n.png)
else-> //您的Imageview占位符图标
}