本文介绍了如何同时处理OnTouchListener事件和OnClickListener事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有RecyclerView,并且将每个项目设置为OnTouchListenerOnClickListener

I have RecyclerView and I set to each item OnTouchListener and OnClickListener

OnTouchListener:

override fun onBindViewHolder(holder: ItemListViewHolder, position: Int) {
    val item = getItem(position)
    holder.bind(item)
    holder.itemView.cardview.setOnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_DOWN) {
            Log.d(TAG, "onBindViewHolder: $event.buttonState")
            this.startDragListener.onStartDrag(holder)
        }
        return@setOnTouchListener true
    }
}

OnClickListener:(在视图持有者内部)

OnClickListener:(inside the view holder)

 init {
    itemView.setOnClickListener(this)
}

 override fun onClick(v: View?) {
        onItemClickListener.onItemClick(adapterPosition)
    }

问题是当我单击该项目时,仅触发了startDragListener,而单击事件从未触发.

The problem is when I click on the item, only the startDragListener triggered, but the on click event never triggered.

关于这个问题,我在stackoverflow上读到了类似的问题,但其中大多数是非常旧的/过时的方法

I read some similar question on stackoverflow about this problem, but most of them are very old/deprecated method

我该如何解决此问题并同时处理触摸侦听器和单击侦听器?

How can I solve this problem and handle both touch listeners and click listeners?

推荐答案

请参见,onClickListener不能与onTouchListener一起使用.您将必须实现一些逻辑,以区分onTouchListener中的单击和拖动.我做了这样的事情,代码在Java中,但是您可以找到一个主意.

See, onClickListener won't work with onTouchListener. You will have to implement some logic to differentiate between click and drag in onTouchListener. I did something like this, code is in java but you can get an idea.

switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN:
            x = motionEvent.getX();
            y = motionEvent.getY();
            return true;

        case MotionEvent.ACTION_UP:
            // PUT ON CLICK LOGIC HERE
            break;
        case MotionEvent.ACTION_MOVE:
            if ((motionEvent.getX() - x) > 80 || (x - motionEvent.getX()) > 80
                    || (motionEvent.getY() - y) > 50 || (y - motionEvent.getY()) > 60) {
                    view.startDrag(data, new View.DragShadowBuilder(view) {
                        @Override
                        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
                            shadowSize.set(view.getWidth(), view.getHeight());
                            shadowTouchPoint.set((int) motionEvent.getX(), (int) motionEvent.getY());
                        }
                    }, view, 0);
            }
            return true;

    }

这篇关于如何同时处理OnTouchListener事件和OnClickListener事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 12:17