Android Kotlin New intent on click event from recycler view

回眸只為那壹抹淺笑 提交于 2020-12-13 03:11:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!