如何在适配器中的kotlin中提供长时间单击侦听器

gfttwv5a  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(298)

如何在适配器中实现长时间单击侦听器?我已经通过接口实现了onclicklister。但我不知道如何实现长点击侦听器。
这是适配器

class DokladAdapter(private val listener: OnItemClickListener): ListAdapter<DokladTuple, DokladAdapter.PolozkaViewHolder>(DiffCallback()) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PolozkaViewHolder {
        val binding = DokladyItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return PolozkaViewHolder(binding)
    }

    override fun onBindViewHolder(holder: PolozkaViewHolder, position: Int) {
        val currentItem = getItem(position)
        if (currentItem != null) {
            holder.bind(currentItem)
        }
    }

    inner class PolozkaViewHolder(private val binding: DokladyItemBinding): RecyclerView.ViewHolder(binding.root) {
        init {
            binding.root.setOnClickListener{
                val position = bindingAdapterPosition
                if (position != RecyclerView.NO_POSITION){
                    val item = getItem(position)
                    if (item != null){
                        listener.onItemClick(item)
                    }
                }
            }
        }
        fun bind(polozkaHlavicka: DokladTuple){
            binding.apply {
                tvU.text = "U"
                tvDOKL.text = polozkaHlavicka.doklad.toString()
                //tvODB.text = "200"
                tvORG.text = polozkaHlavicka.odj.toString()
                tvDATUM.text = polozkaHlavicka.datuct.toString()
            }
        }
    }
    interface OnItemClickListener{
        fun onItemClick(polozkaHlavicka: DokladTuple)
    }

    class DiffCallback: DiffUtil.ItemCallback<DokladTuple>(){
        override fun areItemsTheSame(oldItem: DokladTuple, newItem: DokladTuple) =
            oldItem.doklad == newItem.doklad

        override fun areContentsTheSame(oldItem: DokladTuple, newItem: DokladTuple) =
            oldItem == newItem
    }
}

我在活动中有覆盖功能

class Activity: AppCompatActivity(), PolozkaAdapter.OnItemClickListener{
override fun onItemClick(polozkaDoklad: PolozkaTuple) {
        //TODO - do something
    }
}
eeq64g8w

eeq64g8w1#

更新您的 OnItemClickListener 将长单击处理程序包括为

interface OnItemClickListener{ 
    fun onClick(polozkaHlavicka: DokladTuple)
    fun onLongClick(polozkaHlavicka: DokladTuple)
}

现在在
PolozkaViewHolder init 添加 longClickListener 作为

binding.root.setOnLongClickListener{
    // get position data and call long click handler 
    //listener.onLongClick()
}

最后更新的实现 OnItemClickListener 在里面 Activity 对于 onLongClick

相关问题