10.3 Drawing the data in the UI
MainActivity
code changes a little, because now we have real data to fill the adapter. The
asynchronous call needs to be rewritten:
10 Parsing data
37
1
async() {
2
val result = RequestForecastCommand("94043").execute()
3
uiThread {
4
forecastList.adapter = ForecastListAdapter(result)
5
}
6
}
The adapter needs some modifications too:
1
class ForecastListAdapter(val weekForecast: ForecastList) :
2
RecyclerView.Adapter() {
3
4
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
5
ViewHolder? {
6
return ViewHolder(TextView(parent.getContext()))
7
}
8
9
override fun onBindViewHolder(holder: ViewHolder,
10
position: Int) {
11
with(weekForecast.dailyForecast[position]) {
12
holder.textView.text = "$date - $description - $high/$low"
13
}
14
}
15
16
override fun getItemCount(): Int = weekForecast.dailyForecast.size
17
18
class ViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)
19
}
with
function
with
is a useful function included in the standard Kotlin library. It basically receives an
object and an extension function as parameters, and makes the object execute the function.
This means that all the code we define inside the brackets acts as an extension function
of the object we specify in the first parameter, and we can use all its public functions and
properties, as well as
this
. Really helpful to simplify code when we do several operations
over the same object.
There’s a lot of new code in this chapter, so feel free to check it out on the
repository¹⁸
.
¹⁸
https://github.com/antoniolg/Kotlin-for-Android-Developers
Do'stlaringiz bilan baham: |