Skip to content

Commit

Permalink
Step.05-Solution-Refactor-onBindViewHolder
Browse files Browse the repository at this point in the history
  • Loading branch information
iambryanwho authored and “Murat committed Jun 5, 2019
1 parent 0a184ed commit 7b71416
Showing 1 changed file with 18 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,27 +40,7 @@ class SleepNightAdapter : RecyclerView.Adapter<SleepNightAdapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = data[position]

// TODO (04) Move the res variable to ViewHolder.bind().

val res = holder.itemView.context.resources

// TODO (01) Refactor binding logic into a separate function called bind().

// TODO (02) Convert the bind() function's holder parameter to a receiver.

// TODO (03) Move bind() into the ViewHolder class.

holder.sleepLength.text = convertDurationToFormatted(item.startTimeMilli, item.endTimeMilli, res)
holder.quality.text = convertNumericQualityToString(item.sleepQuality, res)
holder.qualityImage.setImageResource(when (item.sleepQuality) {
0 -> R.drawable.ic_sleep_0
1 -> R.drawable.ic_sleep_1
2 -> R.drawable.ic_sleep_2
3 -> R.drawable.ic_sleep_3
4 -> R.drawable.ic_sleep_4
5 -> R.drawable.ic_sleep_5
else -> R.drawable.ic_sleep_active
})
holder.bind(item)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
Expand All @@ -72,9 +52,26 @@ class SleepNightAdapter : RecyclerView.Adapter<SleepNightAdapter.ViewHolder>() {
}

class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){

val sleepLength: TextView = itemView.findViewById(R.id.sleep_length)
val quality: TextView = itemView.findViewById(R.id.quality_string)
val qualityImage: ImageView = itemView.findViewById(R.id.quality_image)

fun bind(item: SleepNight) {
val res = itemView.context.resources

sleepLength.text = convertDurationToFormatted(item.startTimeMilli, item.endTimeMilli, res)
quality.text = convertNumericQualityToString(item.sleepQuality, res)
qualityImage.setImageResource(when (item.sleepQuality) {
0 -> R.drawable.ic_sleep_0
1 -> R.drawable.ic_sleep_1
2 -> R.drawable.ic_sleep_2
3 -> R.drawable.ic_sleep_3
4 -> R.drawable.ic_sleep_4
5 -> R.drawable.ic_sleep_5
else -> R.drawable.ic_sleep_active
})
}
}

}

0 comments on commit 7b71416

Please sign in to comment.