更好地了解onTouchListener

时间:2018-10-23 20:57:48

标签: android ontouchlistener

我遇到了一些奇怪的事情,我想听听点击的声音,当它发生时我想得到它的指示,但是点击似乎发生了三次,这是什么原因?

this.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
                int x = (int) motionEvent.getX();
                int y = (int) motionEvent.getY();
                Log.i(LOGGING_CONST, "click performed x: " + x + " y: " + y);
            }
        }
    });

@Override
public boolean performClick() {
    return super.performClick();
}

一键单击后的Logcat:

I/GAME_VIEW_CLASS:: click performed x: 481 y: 804
I/GAME_VIEW_CLASS:: click performed x: 481 y: 804
I/GAME_VIEW_CLASS:: click performed x: 481 y: 804

2 个答案:

答案 0 :(得分:2)

因为您正在侦听触摸事件,并且每次手指移动都会触发触摸事件。尝试监听onDown事件。作为示例;

        this.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    int x = (int) event.getX();
                    int y = (int) event.getY();
                    Log.i(LOGGING_CONST, "click performed x: " + x + " y: " + y);
                    break;
            }
            return true;
        }
    });

答案 1 :(得分:0)

您正在监听ACTION_DOWN,ACTION_MOVE,ACTION_CANCEL等所有触摸事件

如果您想单击一下,然后独自听ACTION_DOWN,

switch(event.ACTION_DOWN):

{

在这里单击即可执行代码

}

请参考以下链接:

https://developer.android.com/reference/android/view/MotionEvent