java Android - 如何检测屏幕上的触摸是“滚动”触摸?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35293125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:57:45  来源:igfitidea点击:

Android - how to detect a touch on screen is a "scroll" touch?

javaandroidandroid-scrollviewandroid-touch-event

提问by Pedro A

I am creating an android app in Java in which I have a lot of <TextView>around the screen, all of them with onTouchListeners defined. They are wrapped in a <ScrollView>because they occupy more space than available in the screen.

我正在用 Java 创建一个 android 应用程序,其中我<TextView>在屏幕上有很多东西,所有这些都定义了 onTouchListeners。它们被包裹在 a 中,<ScrollView>因为它们占用的空间比屏幕中可用的空间多。

My problem is: when I scroll the app, up/down, by touching at the screen and moving my finger up/down, the scroll works as expected but the onTouchListener of the touched <TextView>is also fired (which is probably expected as well) - I don't want that to happen though. I want the onTouchListener to be ignored when I'm touching the screen to scroll it.

我的问题是:当我向上/向下滚动应用程序时,通过触摸屏幕并向上/向下移动我的手指,滚动按预期工作,但触摸的 onTouchListener<TextView>也被触发(这也可能是预期的)-我不希望这种情况发生。当我触摸屏幕滚动它时,我希望 onTouchListener 被忽略。

How can I accomplish this? I don't want my function to run when the user is scrolling and "accidentally" fires the onTouchListener on a certain <TextView>.

我怎样才能做到这一点?我不希望我的函数在用户滚动时运行并“意外地”在某个<TextView>.

回答by Pedro A

After searching more, I found this solutionby Stimsoni. The idea is to check if the time between the ACTION_DOWNand ACTION_UPevents is lower or higher than the value given by ViewConfiguration.getTapTimeout().

在搜索更多之后,我找到了 Stimsoni 的这个解决方案。这个想法是检查ACTION_DOWNACTION_UP事件之间的时间是否低于或高于由 给出的值ViewConfiguration.getTapTimeout()

From the documentation:

从文档:

[Returns] the duration in milliseconds we will wait to see if a touch event is a tap or a scroll. If the user does not move within this interval, it is considered to be a tap.

[返回] 我们将等待查看触摸事件是点击还是滚动的持续时间(以毫秒为单位)。如果用户在此间隔内没有移动,则认为是轻敲。

Code:

代码:

view.setOnTouchListener(new OnTouchListener() {

    private long startClickTime;

    @Override
    public boolean onTouch(View view, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            startClickTime = System.currentTimeMillis();

        } else if (event.getAction() == MotionEvent.ACTION_UP) {

            if (System.currentTimeMillis() - startClickTime < ViewConfiguration.getTapTimeout()) {

                // Touch was a simple tap. Do whatever.

            } else {

                // Touch was a not a simple tap.

            }

        }

        return true;
    }

});

回答by mm49307

I had the same problem as you, and I solved it with ACTION_CANCEL.

我遇到了和你一样的问题,我用ACTION_CANCEL.

motionEvent.getActionMasked()is equal to ACTION_CANCELwhen an action perceived previously (like ACTION_DOWNin your case) is "canceled" now by other gestures like scrolling, etc. your code may be like this:

motionEvent.getActionMasked()等于ACTION_CANCEL以前感知的动作(例如ACTION_DOWN在您的情况下)现在被其他手势(如滚动等)“取消”时。您的代码可能是这样的:

view.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent e) {
        if (e.getActionMasked() == MotionEvent.ACTION_DOWN) {
            // perceive a touch action.
        } else if(e.getActionMasked() == MotionEvent.ACTION_UP ||
                e.getActionMasked() == MotionEvent.ACTION_CANCEL) {
            // ignore the perceived action.      
        }
    }

I hope this helps.

我希望这有帮助。

回答by Matteljay

I had a similar problem but with one TextView, search led me here. The text-content potentially takes up more space than available on screen. Simple working example: bpmcounter-android(Kotlin)

我遇到了类似的问题,但是使用一个 TextView,搜索将我带到了这里。文本内容可能会占用比屏幕上可用空间更多的空间。简单的工作示例:bpmcounter-android(Kotlin)

class MainActivity : AppCompatActivity() {

    inner class GestureTap : GestureDetector.SimpleOnGestureListener() {
        override fun onSingleTapUp(e: MotionEvent?): Boolean {
            // Do your buttonClick stuff here. Any scrolling action will be ignored
            return true
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView = findViewById<TextView>(R.id.textView)
        textView.movementMethod = ScrollingMovementMethod()
        val gestureDetector = GestureDetector(this, GestureTap())
        textView.setOnTouchListener { _, event -> gestureDetector.onTouchEvent(event) }
    }
}

回答by Mattia Ferigutti

1 METHOD:

1 方法:

I figured out that the best method to do this is detecting the first touch saving the points x and y and then confront it with the second touch. If the distance between the first click and the second one is quite close (I put 10% as an approximation) then the touch a simple click otherwise is a scrolling movement.

我发现最好的方法是检测保存点 x 和 y 的第一次触摸,然后用第二次触摸来面对它。如果第一次点击和第二次点击之间的距离很近(我把 10% 作为近似值),那么触摸一个简单的点击就是滚动运动。

 /**
 * determine whether two numbers are "approximately equal" by seeing if they
 * are within a certain "tolerance percentage," with `tolerancePercentage` given
 * as a percentage (such as 10.0 meaning "10%").
 *
 * @param tolerancePercentage 1 = 1%, 2.5 = 2.5%, etc.
 */
fun approximatelyEqual(desiredValue: Float, actualValue: Float, tolerancePercentage: Float): Boolean {
    val diff = Math.abs(desiredValue - actualValue) //  1000 - 950  = 50
    val tolerance = tolerancePercentage / 100 * desiredValue //  20/100*1000 = 200
    return diff < tolerance //  50<200      = true
}

var xPoint = 0f
var yPoint = 0f
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
    when(event.action) {

        MotionEvent.ACTION_DOWN -> {
            xPoint = event.x
            yPoint = event.y
            return true
        }

        MotionEvent.ACTION_UP -> {
            if (!approximatelyEqual(xPoint, event.x, 10f) || !approximatelyEqual(yPoint, event.y, 10f)) {
                //scrolling
            } else {
                //simple click
            }
        }
    }
    return false
}

2 METHOD:

2 方法:

Another way to do the same thing is by using the GestureDetector class:

另一种做同样事情的方法是使用 GestureDetector 类:

   interface GestureInterface {
    fun setOnScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float)
    fun onClick(e: MotionEvent)
}

class MyGestureDetector(val gestureInterfacePar: GestureInterface) : SimpleOnGestureListener() {

    override fun onSingleTapUp(e: MotionEvent): Boolean { 
        gestureInterfacePar.onClick(e)
        return false
    }

    override fun onLongPress(e: MotionEvent) {}
    override fun onDoubleTap(e: MotionEvent): Boolean {
        return false
    }

    override fun onDoubleTapEvent(e: MotionEvent): Boolean {
        return false
    }

    override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
        return false
    }

    override fun onShowPress(e: MotionEvent) {
    }

    override fun onDown(e: MotionEvent): Boolean { 
        return true
    }

    override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
        gestureInterfacePar.setOnScroll(e1, e2, distanceX, distanceY)
        return false
    }

    override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { 
        return super.onFling(e1, e2, velocityX, velocityY)
    }
}

and finally, bind it with your view:

最后,将它与您的视图绑定:

val mGestureDetector = GestureDetector(context, MyGestureDetector(object : GestureInterface {
                override fun setOnScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float) {
                    //handle the scroll
                }

                override fun onClick(e: MotionEvent) {
                    //handle the single click
                }

            }))


            view.setOnTouchListener(OnTouchListener { v, event -> mGestureDetector.onTouchEvent(event) })

回答by Safwen Chaieb

Worked for me :

对我来说有效:

View.OnTouchListener() {

View.OnTouchListener() {

    @Override

public boolean onTouch(View v,MotionEvent event)

public boolean onTouch(View v,MotionEvent 事件)

{

{

        if(event.getAction()!=MotionEvent.ACTION_DOWN)

        {

                     // Before touch

        }

        else {

                      // When touched

                }

                          return true

});

回答by justDroid

You can identify moving action like this:

您可以像这样识别移动动作:

view.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if(event.getAction() == MotionEvent.ACTION_MOVE)
            {

            }

            return false;
        }
    });