Responding to Presses

As icing on the RecyclerView cake, CriminalIntent should also respond to a press on these list items. In Chapter 12, you will launch the detail view for a Crime when the user presses on that Crime in the list. For now, show a Toast when the user takes action on a Crime.

As you may have noticed, RecyclerView, while powerful and capable, has precious few real responsibilities. (May it be an example to us all.) The same goes here: Handling touch events is mostly up to you. If you need them, RecyclerView can forward along raw touch events. But most of the time this is not necessary.

Instead, you can handle them like you normally do: by setting an OnClickListener. Since each View has an associated ViewHolder, you can make your ViewHolder the OnClickListener for its View.

Modify the CrimeHolder to handle presses for the entire row.

Listing 9.15  Detecting presses in CrimeHolder (CrimeListFragment.kt)

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

    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)

    init {
        itemView.setOnClickListener(this)
    }

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

    override fun onClick(v: View) {
        Toast.makeText(context, "${crime.title} pressed!", Toast.LENGTH_SHORT)
                .show()
    }
}

In Listing 9.15, the CrimeHolder itself is implementing the OnClickListener interface. On the itemView, which is the View for the entire row, the CrimeHolder is set as the receiver of click events.

Run CriminalIntent and press on an item in the list. You should see a Toast indicating that the item was pressed.

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

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