如何使用interfce生成点击事件并从recyclerview获取价值。
MainActivity.kt
class Company : AppCompatActivity(),CompanyAdapter.Listner{
override fun onItemCompanyClick(company: Company) {
Toast.makeText(this, "You clicked: ${company.Cmp_Name}", Toast.LENGTH_LONG).show()
}
}
CompanyAdapter.kt
class CompanyAdapter(private val listner :Listner, internal var companyList: List<Company>)
:RecyclerView.Adapter<CompanyAdapter.CompanyViewHolder>()
{
interface Listner {
fun onItemCompanyClick(company: Company)
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): CompanyViewHolder {
val itemView = LayoutInflater.from(p0.context).inflate(R.layout.list_view_item,p0,false)
return CompanyViewHolder(itemView)
}
override fun getItemCount(): Int {
return companyList.size
}
override fun onBindViewHolder(p0: CompanyViewHolder, p1: Int) {
// p0.rbButton.text = this!!.companyList?.get(p1)?.Cmp_Name
p0.bindModel(companyList[p1])
}
inner class CompanyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val radioButton : RadioButton = itemView.findViewById(R.id.rbCompanyName)
fun bindModel(company: Company){
radioButton.text = company.Cmp_Name
}
}
}
答案 0 :(得分:0)
从不调用您的界面,如果用户单击按钮,则应该调用。
尝试类似的东西:
MainActivity.kt
class Company : AppCompatActivity(),CompanyAdapter.Listner{
override fun onItemCompanyClick(company: Company){
Toast.makeText(this, "You clicked: ${company.Cmp_Name}", Toast.LENGTH_LONG).show()
}
}
CompanyAdapter.kt
class CompanyAdapter(private val listner :Listner, internal var companyList: List<Company>)
:RecyclerView.Adapter<CompanyAdapter.CompanyViewHolder>()
{
interface Listner{
fun onItemCompanyClick(company: Company)
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): CompanyViewHolder {
val itemView = LayoutInflater.from(p0.context).inflate(R.layout.list_view_item,p0,false)
return CompanyViewHolder(itemView)
}
override fun getItemCount(): Int {
return companyList.size
}
override fun onBindViewHolder(p0: CompanyViewHolder, p1: Int) {
// p0.rbButton.text = this!!.companyList?.get(p1)?.Cmp_Name
p0.bindModel(companyList[p1])
}
inner class CompanyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val radioButton : RadioButton = itemView.findViewById(R.id.rbCompanyName)
fun bindModel(company: Company){
radioButton.text = company.Cmp_Name
radioButton.setOnClickListener(_ -> listner.onItemCompanyClick(company))
}
}
}
也请阅读this guide about interface,希望对您有所帮助。