Implementing a ViewHolder

The RecyclerView expects an item view to be wrapped in an instance of ViewHolder. A ViewHolder stores a reference to an item’s view (and sometimes references to specific widgets within that view).

Define a view holder by adding an inner class in CrimeListFragment that extends from RecyclerView.ViewHolder.

Listing 9.9  The beginnings of a ViewHolder (CrimeListFragment.kt)

class CrimeListFragment : Fragment() {
    ...
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        ...
    }

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

    }
}

In CrimeHolder’s constructor, you take in the view to hold on to. Immediately, you pass it as the argument to the RecyclerView.ViewHolder constructor. The base ViewHolder class will then hold on to the view in a property named itemView (Figure 9.6).

Figure 9.6  The ViewHolder and its itemView

The ViewHolder and its itemView

A RecyclerView never creates Views by themselves. It always creates ViewHolders, which bring their itemViews along for the ride (Figure 9.7).

Figure 9.7  The ViewHolder visualized

The ViewHolder visualized

When the View for each item is simple, ViewHolder has few responsibilities. For more complicated Views, the ViewHolder makes wiring up the different parts of itemView to a Crime simpler and more efficient. (For example, you do not need to search through the item view hierarchy to get a handle to the title text view every time you need to set the title.)

Update CrimeHolder to find the title and date text views in itemView’s hierarchy when an instance is first created. Store references to the text views in properties.

Listing 9.10  Pulling out views in the constructor (CrimeListFragment.kt)

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

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

The updated view holder now stashes references to the title and date text views so you can easily change the value displayed later without having to go back through the item’s view hierarchy (Figure 9.8).

Figure 9.8  The ViewHolder re-visualized

The ViewHolder re-visualized

Note that the CrimeHolder assumes that the view passed to its constructor has child text views with the IDs R.id.crime_title and R.id.crime_date. You may be wondering, Who (or what) creates crime holder instances, and can I safely assume the view hierarchy passed to the constructor contains the child widgets I expect? You will learn the answer to these questions in just a moment.

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

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