I was doing a Kotlin course and this question arose: do all views have a context? It may be due to the lack of knowledge in understanding well and in a "simple" way what is the context in an Android app.
For example, I know that in an Adapter when we want to access the context we can access it through the holder provided by the onBindViewHolder method, but what is the difference of obtaining it through the itemView itself that can receive the ViewHolder class that we create in the adaptor? Or the difference of getting it through a setOnClickListener that we do to a button.
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
private val mediaItemTitle: TextView = itemView.findViewById(R.id.mediaTitle)
private val mediaItemImage: ImageView = itemView.findViewById(R.id.mediaThumb)
fun bind(mediaItem: MediaItem) {
mediaItemTitle.text = mediaItem.title
mediaItemImage.loadUrl(mediaItem.imageUrl)
itemView.setOnClickListener {
itemView.context.toast(mediaItem.title)
}
}
}
Then another question arises: do all components of a view have a context? An ImageView, a TextView, and a CustomView that we call on our view too?
What ways are there to call the context and which are the safest without the risk of getting a leak. An easy way to get a context in an adapter would be to pass the context of the activity or fragment where we are going to use it as a constructor, but I know that this would cause a memory leak. Let's see if you can help me a little since I want to take note of these cases to know what would be the most optimal way in each possible case.
Yes, all views have a context.
Look at its constructors, for example of an ImageView:
ViewGrups extend View so they also have a context.
Try to avoid passing the context to an adapter because you don't really need it, what needs to change is the approach you're following. For example, what an adapter does is bridge between the view and the ViewHolder, and the ViewHolder is the cell that will populate the item and also capture the clicks. But beware, capturing the click does not mean implementing any behavior. The behavior will be implemented by the Activity/Fragment, for example, to display a Toast, navigation, permission management... always respecting the architecture you are using. For this you can use a callback (interface) or a lambda, in Kotlin it is a higher order function.