简体   繁体   English

MotionEvent从ACTION_UP更改为ACTION_DOWN

[英]MotionEvent changes from ACTION_UP to ACTION_DOWN

In this code: 在此代码中:

private static MotionEvent e1;
private static float start;

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getActionMasked() == MotionEvent.ACTION_UP) {
        MotionEvent e2 = event;
        float velocityX = Math.abs((e1.getX() - e2.getX()) / start);
        float velocityY = Math.abs((e1.getY() - e2.getY()) / start);
        onFling(e1, event, velocityX, velocityY);//BREAKPOINT 2
    } else if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
        e1 = event;
        start = System.currentTimeMillis() / 1000;//BREAKPOINT 1
    }
    return Game.onTouchEvent(event);
}

If I put a break point on the "BREAKPOINT 1" line, I get that: e1.getActionMasked() equals ACTION_DOWN . 如果在“ BREAKPOINT 1”行上放置一个断点, e1.getActionMasked()得到: e1.getActionMasked()等于ACTION_DOWN But when it stops in "BREAKPOINT 2" I get that e1 equals event . 但是当它在“ BREAKPOINT 2”中停止时,我得到e1等于event Also if I add && event != e1 to the first "if" the code in it is skipped.Why is this happening? 另外,如果我将&& event != e1添加到第一个“ if”中,则会跳过其中的代码。为什么会这样?

If you want to know why I am using this approach to replace onFling() see this: onFling not being called in a costum View 如果您想知道为什么我使用这种方法替换onFling()请参见以下内容: 在costum视图中未调用onFling

Android does some memory optimization here. Android在这里做了一些内存优化。 Since touch events happen really a lot during the gesture - instead of creating MotionEvent instance every time onTouchEvent happens, Android reuses previous MotionEvent instance, so you don't pollute your heap memory. 由于触摸事件的手势期间真的发生了很多-而不是创建MotionEvent每次实例onTouchEvent发生,Android的重用以前的MotionEvent的实例,这样你就不会污染您的堆内存。

Since you store the reference to MotionEvent (ACTION_DOWN) in your case - your ev1 is getting updated every time onTouchEvent is called. 既然你存储参考MotionEvent你的情况(ACTION_DOWN) -你的ev1是得到更新,每次onTouchEvent被调用。 That's why when ACTION_UP happens - your ev1 equals to the latest motion event. 这就是为什么当ACTION_UP发生时-您的ev1等于最新的运动事件。 It is the same instance as it used to be during ACTION_DOWN . 它与ACTION_DOWN期间的实例相同。

Instead of storing MotionEvent instance - you need to store x and y coordinates during ACTION_DOWN 而不是存储MotionEvent实例-您需要在ACTION_DOWN期间存储xy坐标

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM