Cleaning Up Binding List Items

Right now, the Adapter binds crime data directly to a crime holder’s text views in Adapter.onBindViewHolder(…). This works fine, but it is better to more cleanly separate concerns between the view holder and the adapter. The adapter should know as little as possible about the inner workings and details of the view holder.

We recommend you place all the code that will do the real work of binding inside your CrimeHolder. First, add a property to stash the Crime being bound. While you are at it, make the existing text view properties private. Add a bind(Crime) function to CrimeHolder. In this new function, cache the crime being bound into a property and set the text values on titleTextView and dateTextView.

Listing 9.13  Writing a bind(Crime) function (CrimeListFragment.kt)

private inner class CrimeHolder(view: View)
    : RecyclerView.ViewHolder(view) {

    private lateinit var crime: Crime

    private val titleTextView: TextView = itemView.findViewById(R.id.crime_title)
    private val dateTextView: TextView = itemView.findViewById(R.id.crime_date)

    fun bind(crime: Crime) {
        this.crime = crime
        titleTextView.text = this.crime.title
        dateTextView.text = this.crime.date.toString()
    }
}

When given a Crime to bind, CrimeHolder will now update the title TextView and date TextView to reflect the state of the Crime.

Next, call your newly minted bind(Crime) function each time the RecyclerView requests that a given CrimeHolder be bound to a particular crime.

Listing 9.14  Calling the bind(Crime) function (CrimeListFragment.kt)

private inner class CrimeAdapter(var crimes: List<Crime>)
    :  RecyclerView.Adapter<CrimeHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CrimeHolder {
        ...
    }

    override fun onBindViewHolder(holder: CrimeHolder, position: Int) {
        val crime = crimes[position]
        holder.apply {
            titleTextView.text = crime.title
            dateTextView.text = crime.date.toString()
        }
        holder.bind(crime)
    }

    override fun getItemCount() = crimes.size
}

Run CriminalIntent one more time. The result should look the same as it did in Figure 9.11.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.79.88