问题
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)
}
}
回答1:
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)
来源:https://stackoverflow.com/questions/59012821/android-kotlin-new-intent-on-click-event-from-recycler-view