简体   繁体   中英

How to call Context and Intent objects inside onBindViewHolder

I want to open a new Activity within RecyclerView , but I can't create an Intent object in there.

val intent1 = Intent(this,Main2Activity::class.java)   
startActivity(intent1) 

Android Studio warns about Intent not being a Context . How can I still open a new Activity inside the RecyclerView

在此处输入图片说明

I tried also the code below,it gives "startActivity(intent)" line gives error, "type mismatch, required Context, found Intent".

Plus, also "this@MainActivity" gives "unresolved reference@MainActivity" error.

  override fun onBindViewHolder(holder: Main_Menu_Holder, position: Int) {
        var currentview = alldata.get(position)

    }

You are calling this which is your RecyclerView 's onBindViewHolder . You have to call the Context using View :

  override fun onBindViewHolder(holder: Main_Menu_Holder, position: Int, v:View) {
        val intent = Intent(v.context, Main2activity::class.java)
        startActivity(intent) 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM