上一篇文章介紹天氣資訊畫面的設計,但是天氣狀況的圖示尚未完成。 本篇文章將介紹使用Glide來顯示各種天氣圖示,並且修正程式碼讓城市名可以在畫面上顯示出來。
https://github.com/scobin/Android_WeatherApp/tree/feature/addGildeLib
開啟 app 資料夾下的buid.gradle檔案,加入以下程式碼。 完成後執行「sync now」。
// glide
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
在WeatherDetailRecyclerAdapter的onBindViewHolder函數中加入Glide程式碼。 with中設置 holder.itemView。 load中設置圖片URL。(https://openweathermap.org/img/wn/"+ weather.weather[0].icon + "@2x.png) into裡則是要放上圖片的畫面元件,這裡設置成 holder.itemView.weather_icon。
override fun onBindViewHolder(holder: WeatherDetailRecyclerHolder, position: Int) {
...
Glide.with(holder.itemView)
.load("https://openweathermap.org/img/wn/"+ weather.weather[0].icon + "@2x.png")
.into(holder.itemView.weather_icon)
}
上一段影片在WeatherDetailFragment中產生了viewModel物件但尚未設定到databinding上,因此城市名無法被顯示。 只要將viewModel物件設定好即可顯示城市名。
override fun onActivityCreated(savedInstanceState: Bundle?) {
...
viewModel = ViewModelProviders.of(this).get(WeatherDetailViewModel::class.java)
binding.viewModel = viewModel // <-- 設定viewModel
val adapter = WeatherDetailRecyclerAdapter(arrayListOf())
...
}