我创建了一个简单的Adapter
。我想在用户点击某个项目时从Activity
内启动Adapter
。我无法获得context
中的onClick
。我在onClick
课程中执行了MyViewHolder
。这是我的适配器代码:
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"
}
}
}
答案 0 :(得分:1)
您在该行收到错误,因为Intents未按此声明。您还需要提供一个java Class作为第二个参数。
有关获取Intent对象的正确方法,请参阅documentation。
修改强>
关于我的评论,您需要将ViewHolder类声明为内部类。即:
inner class MyViewHolder(holder: View) : RecyclerView.ViewHolder(holder){}
如Kotlin Reference Manual中所述,除非修改为内部类,否则嵌套类将无法访问外部类&#39;成员。