I started android development a few days ago. I implemented a recylerview and in the OnBindViewHolder method of the recyclerview adapter I used the setOnClickListener on the recyclerview item. My main goal was to start a new activity when the recyclerview item is clicked but I ran into a wall when implementing my code in the following way:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val clusterItem = datalist[position]
holder.clusterName.setText(clusterItem.name)
holder.clusterStrat.setText(clusterItem.strats)
holder.itemview.setOnClickListener() {
startActivity(Intent(holder.itemview.context,ClusterSearchActivity::class.java))
}
}
I had 3 errors on the line that contains startActivity:
Type mismatch: inferred type is Intent but Context was expected
No value passed for parameter 'intent'
No value passed for parameter 'options'
After going through multiple solutions I finally stumbled upon this one: https://www.titanwolf.org/Network/q/08ad14d9-cb9a-4b87-923b-f97089db769a/y
Using context.startActivity(intent) I rewrote my code like this:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val clusterItem = datalist[position]
holder.clusterName.setText(clusterItem.name)
holder.clusterStrat.setText(clusterItem.strats)
holder.itemview.setOnClickListener() {
holder.itemview.context.startActivity(Intent(holder.itemview.context,ClusterSearchActivity::class.java)) }
}
Now my code finally worked but I can't seem to understand why I had to use context.startActivity(). I'd like to understand when can I use startActivity() just like that and when I need to use context.startActivity().