0

所以我正在使用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")
            }

        })
    }
}

4

1 回答 1

0

使用时间

当(“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 的占位符图标

}

于 2018-10-19T04:07:52.080 回答