Asa Carter
Asa Carter

Reputation: 2225

Android Kotlin New intent on click event from recycler view

I've just started learning android development with Kotlin.

I have a recycler view that lists items.

I'm trying to create onClick event for the item and then start a new intent and pass along the item id.

I'm getting an error when trying to instantiate the Intent "None of the following functions can be called with the arguments supplied". I think it's because I cannot access the context of the view?

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.id = events[position][0]
    holder.title.text = events[position][1]

    if (events[position][2] == events[position][3]) {
        holder.date.text = events[position][2]
    } else {
        holder.date.text = events[position][2] + " - " + events[position][3]
    }

    holder.itemView.setOnClickListener {
        v: View -> Unit


        Log.d(TAG, "onItemClick for ID: " + holder.id)

        val intent = Intent(this, EventDetail::class.java)
        intent.putExtra("id", holder.id)
        startActivity(intent)
    }
}

error

Upvotes: 2

Views: 8838

Answers (3)

Tejas Tripathi
Tejas Tripathi

Reputation: 21

you can use holder.itemView.context.startActivity(intent)here is my error

I solved it like this

Solution

Upvotes: 1

Piyush Kalyan
Piyush Kalyan

Reputation: 61

This Comes Under OnBindviewholder in Kotlin '

holder.itemView.setOnClickListener { v ->
            val intent = Intent(v.context, QuestionsActi::class.java)
            v.context.startActivity(intent)

}

'

Upvotes: 6

Mohammed Alaa
Mohammed Alaa

Reputation: 3320

you need a context for intent so you can get it form the activity or fragment that are associated with this adapter and pass it to your intent or you can get it from any view in your inflated layout like this

val context=holder.title.context
val intent = Intent( context, EventDetail::class.java)
context.startActivity(intent)

or you can make a listener that your activity or fragment implement it and you can on it's callback create your intent like this

val intent= Intent( this@YourCalssname,EventDetail::class.java)

Upvotes: 4

Related Questions