簡體   English   中英

如何在 Kotlin 中的 RecyclerView 上實現 longClickListen

[英]how to implement longClickListen on RecyclerView in Kotlin

在搜索了幾個小時的解決方案后,我可以實現 ItemClickListener 但由於某種原因,我無法使用相同的方法來實現 itomLongClickListener。 它給了我“類型不匹配”錯誤:類型不匹配。 必需:布爾值 找到:單位

如果您能指出我做錯了什么,我將不勝感激。

下面是我的代碼

class MyAdapter(ct: Context, s1: Array<String>, s2: Array<String>?):RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
    var nameList: Array<String>? = null
    var oneLineMessage: Array<String>? = null
    var context: Context? = null

    init {
        nameList = s1
        oneLineMessage = s2
        context = ct

    }

    fun onClick(view :View){
        val intent= Intent(context,SecondPage::class.java)
        context?.startActivity(intent)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        var inflater = LayoutInflater.from(context)
        var v = inflater.inflate(R.layout.my_row, parent, false)
        return MyViewHolder(v)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.friendName?.text = nameList?.get(position)
        if (oneLineMessage != null) {
            holder.messagePreview?.text = oneLineMessage?.get(position)
        } else {
            holder.messagePreview?.visibility = View.GONE
        }
        holder.layout?.setOnClickListener(View.OnClickListener {
            val intent= Intent(context,SecondPage::class.java)
            context?.startActivity(intent)
        })
    }

    override fun getItemCount(): Int {
        return nameList?.size as Int
    }

    inner class MyViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var friendName: TextView? = itemView.findViewById(R.id.nameText)
        var messagePreview: TextView? = itemView.findViewById(R.id.messagePreview)
        var layout: RelativeLayout? = itemView.findViewById(R.id.secondPageConstraintLayout)

        init {
            
            itemView.setOnClickListener{
                val position=adapterPosition+1
                Toast.makeText(context, "you chose $position", Toast.LENGTH_SHORT).show()
            }
            
            itemView.setOnLongClickListener(View.OnLongClickListener {
                val position=adapterPosition+1
                Toast.makeText(context, "you long pressed $position", Toast.LENGTH_SHORT).show()  })
        }


    }
}

View.OnLongClickListner是一個帶有boolean onLongClick(View v)的接口,這意味着您必須返回boolean

如果回調消耗了長按,則返回 true,否則返回 false。

show()返回Unit ,這是 lambda {}最后一行

所以如果你長按你的itemView就返回true

itemView.setOnLongClickListener {
    val position=adapterPosition+1
    Toast.makeText(context, "you long pressed $position", Toast.LENGTH_SHORT).show()
    true
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM