The Easy Way: Implicit Intents

You will browse to this URL first by using your old friend the implicit intent. This intent will start up the browser with your photo URL.

The first step is to make your app listen to presses on an item in the RecyclerView. Update PhotoGalleryFragment’s PhotoHolder to implement a click listener that will fire an implicit intent.

Listing 29.2  Firing an implicit intent when an item is pressed (PhotoGalleryFragment.kt)

class PhotoGalleryFragment : VisibleFragment() {
    ...
    private inner class PhotoHolder(private val itemImageView: ImageView)
        : RecyclerView.ViewHolder(itemImageView),
        View.OnClickListener {

        private lateinit var galleryItem: GalleryItem

        init {
            itemView.setOnClickListener(this)
        }

        val bindDrawable: (Drawable) -> Unit = itemImageView::setImageDrawable

        fun bindGalleryItem(item: GalleryItem) {
            galleryItem = item
        }

        override fun onClick(view: View) {
            val intent = Intent(Intent.ACTION_VIEW, galleryItem.photoPageUri)
            startActivity(intent)
        }
    }
    ...
}

Adding the inner keyword to the PhotoHolder allows you to access the outer class’s properties and functions. In this case, you call Fragment.startActivity(Intent) from within PhotoHolder.

Next, bind the PhotoHolder to a GalleryItem in PhotoAdapter.onBindViewHolder(…).

Listing 29.3  Binding GalleryItem (PhotoGalleryFragment.kt)

class PhotoGalleryFragment : VisibleFragment() {
    ...
    private inner class PhotoAdapter(private val galleryItems: List>GalleryItem>) :
            RecyclerView.Adapter<PhotoHolder>() {
        ...
        override fun onBindViewHolder(holder: PhotoHolder, position: Int) {
            val galleryItem = galleryItems[position]
            holder.bindGalleryItem(galleryItem)
            val placeholder: Drawable = ContextCompat.getDrawable(
                requireContext(),
                R.drawable.bill_up_close
            ) ?: ColorDrawable()
            holder.bindDrawable(placeholder)
            thumbnailDownloader.queueThumbnail(holder, galleryItem.url)
        }
    }
    ...
}

That is it. Start up PhotoGallery and press on a photo. Your browser app should pop up and load the photo page for the item you pressed (similar to the image on the left in Figure 29.1).

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

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