Getting JUST onTouch events (Android)

I am trying to separate a few things here.

I have a program with Imagebuttons. They are attached to them.

I want the touch event to be fired ONLY with a touch, not a click. I mean, if I use the mouse to click, for example, I don't want the onTouch event attached to the ImageButton to fire. However, it starts when you click the mouse button above the button.

Is it possible to fire the JUST event when a touch occurs?

My code is:

myImageButton.setOnTouchListener(new Button.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent arg1) { if (arg1.getAction() == android.view.MotionEvent.ACTION_DOWN) { Toast.makeText(LiVoiceActivity.this, "You touched me!", Toast.LENGTH_LONG).show(); } return true; } }); 

Thanks!

+1
source share
1 answer

The MotionEvent class has a field known as Tool_Type. Here I checked the mouse type here:

API 14 AKA EASY MODE

 myImageButton.setOnTouchListener(new Button.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent arg1) { if (arg1.getAction() == android.view.MotionEvent.ACTION_DOWN && (MotionEvent.TOOL_TYPE_MOUSE != arg1.getToolType(0)) { Toast.makeText(LiVoiceActivity.this, "You touched me!", Toast.LENGTH_LONG).show(); } return true; } }); 

API 9

 myImageButton.setOnTouchListener(new Button.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent arg1) { if (arg1.getAction() == android.view.MotionEvent.ACTION_DOWN && (arg1.getSize() > 1) { Toast.makeText(LiVoiceActivity.this, "You touched me!", Toast.LENGTH_LONG).show(); } return true; } }); 

Now it checks the size of the resulting MotionEvent. PRELIMINARY, a mouse click will have a size of 1, so only recognize sizes exceeding 1. Play with this number and see if you can distinguish the mouse from the finger.

0
source

Source: https://habr.com/ru/post/919091/


All Articles