Reputation: 4731
I have created a simple Adapter
. I am trying to start Activity
from within the Adapter
when user clicks on an item. I am not able to get the context
in the onClick
. I am performing onClick
inside MyViewHolder
class. Here is my adapter code:
class LeadListAdapter(context:Context, private val leadList: List<Lead>) : RecyclerView.Adapter<LeadListAdapter.MyViewHolder>() {
var activity:Context = context
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflatedView = parent.inflate(R.layout.custom_lead_row, false)
return MyViewHolder(inflatedView)
}
override fun getItemCount(): Int {
return leadList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindLead(leadList[position])
}
class MyViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
//2
private var view: View = v
private var lead: Lead? = null
//3
init {
v.setOnClickListener(this)
v.trackButton.setOnClickListener(this)
}
//4
override fun onClick(v: View) {
val intent = Intent(activity) //Getting error here
}
fun bindLead(lead: Lead) {
this.lead = lead
view.leadName.text = lead.cusName
view.leadMobileNumber.text = lead.mobileNo.toString()
view.loanAmount.text = lead.amount.toString()
view.leadId.text = "Lead Id: ${lead.id.toString()}"
view.loanType.text = lead.productType
view.loanTypeIcon.text = getCharsFromWords(lead.productType)
}
private fun getCharsFromWords(productType: String?): String? {
val words = productType!!.split(Regex("\\s+"))
val quote: String
val sb = StringBuilder()
for (word in words) {
sb.append(word[0].toString())
}
quote = sb.toString()
return quote
}
companion object {
//5
private val LEAD_KEY = "LEAD"
}
}
}
Upvotes: 0
Views: 7559
Reputation: 1324
You're getting an error at that line because Intents are not declared like that. You need to also supply a java Class as the second parameter.
Refer to the documentation for the correct ways of obtaining an Intent object.
EDIT
In regards to my comment, you need to state your ViewHolder class as a inner class. ie:
inner class MyViewHolder(holder: View) : RecyclerView.ViewHolder(holder){}
As stated in the Kotlin Reference Manual, unless modified as a inner class, nested classes will not have access to the outer class' members.
Upvotes: 2
Reputation: 75788
Unresolved reference context
NOTE
You should return
Context object also.
return MyViewHolder(inflatedView,context)
Then
class MyViewHolder(v: View,context:Context) :
Upvotes: 1