Home > Blockchain >  I can not use .text of textview in onBindviewHolder Method RecyclerVew ViewHolder Like image
I can not use .text of textview in onBindviewHolder Method RecyclerVew ViewHolder Like image

Time:08-17

enter image description here

class CustomAdapter(val itemList: Array<String>) :
    RecyclerView.Adapter<CustomAdapter.MyviewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyviewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.contact_layout, parent, false)

        return MyviewHolder(view)
    }

    override fun onBindViewHolder(holder: MyviewHolder, position: Int) {
        val item = itemList[position]
        holder.itemView.text=item
    }

    override fun getItemCount(): Int {
        return itemList.size
    }


    class MyviewHolder(val view: View) : RecyclerView.ViewHolder(view) {
        val itemView = view.findViewById<TextView>(R.id.contactItem)

    }
}

CodePudding user response:

itemView it's a generic view you've to cast it

Try below code

(holder.itemView as TextView).text = item

CodePudding user response:

Modify it like this:

class CustomAdapter(val itemList: Array<String>) :
    RecyclerView.Adapter<CustomAdapter.MyviewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyviewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.contact_layout, parent, false)

        return MyviewHolder(view)
    }

    override fun onBindViewHolder(holder: MyviewHolder, position: Int) {
        val item = itemList[position]
        (holder as MyviewHolder).bind(item)
    }

    override fun getItemCount(): Int {
        return itemList.size
    }


    class MyviewHolder(view: View) : RecyclerView.ViewHolder(view) {
        fun bind(item: String) {
            val contactItemTextView = itemView.findViewById<TextView>(R.id.contactItem)
            contactItemTextView.text = item
        }

    }
}
  • Related