如何基于OpenWeatherMap API实现Kotlin天气应用背景自动切换?
实现自动根据天气数据切换背景与图标
要让updateUI自动执行,核心是从OpenWeatherMap的API响应里提取天气ID,然后在成功获取到天气数据的逻辑里直接调用这个函数,不用手动传参。具体步骤如下:
1. 定义匹配API响应的数据类
先写对应OpenWeatherMap返回格式的数据类,确保能解析出天气ID:
data class WeatherResponse( val weather: List<WeatherInfo>, // 按需添加其他字段,比如温度、城市名等 ) data class WeatherInfo( val id: Int, // 这就是我们要的天气ID val main: String, val description: String )
2. 发起API请求并自动触发UI更新
以Kotlin常用的Retrofit+协程为例,请求成功后直接提取ID调用updateUI:
Retrofit接口定义
interface WeatherApi { @GET("weather") suspend fun getCurrentWeather( @Query("q") city: String, @Query("appid") apiKey: String, @Query("units") units: String = "metric" ): Response<WeatherResponse> }
在ViewModel或页面中发起请求
private fun fetchWeather(cityName: String) { viewModelScope.launch { runCatching { weatherApi.getCurrentWeather(cityName, YOUR_API_KEY) }.onSuccess { response -> response.body()?.weather?.firstOrNull()?.let { weatherInfo -> // 拿到天气ID后直接调用updateUI updateUI(weatherInfo.id) } }.onFailure { // 处理请求失败的情况,比如弹窗提示 it.printStackTrace() } } }
如果用Volley的话,写法类似:
private fun fetchWeatherWithVolley(cityName: String) { val url = "https://api.openweathermap.org/data/2.5/weather?q=$cityName&appid=$YOUR_API_KEY&units=metric" val request = JsonObjectRequest( Request.Method.GET, url, null, { response -> val weatherArray = response.getJSONArray("weather") if (weatherArray.length() > 0) { val weatherId = weatherArray.getJSONObject(0).getInt("id") updateUI(weatherId) } }, { it.printStackTrace() } ) Volley.newRequestQueue(this).add(request) }
3. 优化updateUI(可选)
原有的if-else链可以用映射表简化,让代码更整洁:
data class WeatherResources(val bgRes: Int, val iconRes: Int) private val weatherResourceMap = mapOf( 200..232 to WeatherResources(R.drawable.thunderstorm_bg, R.drawable.thunderstorm), 300..321 to WeatherResources(R.drawable.drizzle_bg, R.drawable.drizzle), 500..531 to WeatherResources(R.drawable.drizzle_bg, R.drawable.rain), 600..620 to WeatherResources(R.drawable.snow_bg, R.drawable.snow), 701..781 to WeatherResources(R.drawable.mist_bg, R.drawable.mist), 800 to WeatherResources(R.drawable.clear_bg, R.drawable.clear) ) private fun updateUI(id: Int){ val resources = weatherResourceMap.entries.firstOrNull { entry -> id in entry.key || id == entry.key }?.value ?: WeatherResources(R.drawable.clouds_bg, R.drawable.clouds) binding.ivWeatherBg.setImageResource(resources.bgRes) binding.ivWeatherIcon.setImageResource(resources.iconRes) }
之后,只要在合适的时机(比如页面初始化、用户切换城市时)调用fetchWeather,就能自动完成背景和图标的切换了。
内容的提问来源于stack exchange,提问作者KuS-
相关产品推荐
相关产品推荐

