I'm trying to make a touch event that won't be activated until the finger has moved a few units from the initial position.
So far I've set up my onTouch method like this:
private XYEvents xyEvent = new XYEvents();
public boolean motionTracker(MotionEvent event, int n)
{
int note = n;
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
xyEvent.setInitial(event);
playNote(note);
break;
case MotionEvent.ACTION_MOVE:
byte data1;
byte data2;
//I figured I should input a condition to check if the finger has moved a few units before it should start doing stuff like so:
if (xyEvent.getXThreshold(event))
{
int xMod = xyEvent.eventActions(event)[0];
data1 = (byte) (xMod & 0x7f);
data2 = (byte) ((xMod & 0x7f00) >> 8);
xModulation((int)data1, (int)data2);
}
break;
}
This method is the one I'm having problems with:
private float initialX, initialY;
private int xValue;
boolean getXThreshold(MotionEvent event)
{
float deltaX = event.getX();
float threshold = 10;
float condition = (deltaX - initialX);
if(condition <= threshold || condition >= -threshold )
return false;
else
return true;
}
the getXThreshold method seems to do what it's supposed to in another method that looks like this:
public int[] eventActions(MotionEvent event)
{
int value = xValue;
int xNull = 8192;
if(!getXThreshold(event))
xValue = xNull;
if(getXThreshold(event))
xValue = xHandleMove(event, true);
return value;
}
Any suggestions?
/M
It seems that this argument:
if(condition <= threshold || condition >= -threshold )
return false;
else
return true;
Needed to be flipped around, otherwise it always returned false for some reason.
Now it looks like this and works great.
boolean getXThreshold(MotionEvent event)
{
float deltaX = event.getX();
float threshold = 10;
float condition = (deltaX - initialX);
return condition >= threshold || condition <= -threshold;
}
Have a great week!
/M
Related
In my Android game I have implemented a custom code in the onTouchEvent method of a (custom) SurfaceView to emulate a ScrollView. I already tried an actual ScrollView, but due to performance and lack of customizability I preferred to override onTouchEvent myself.
It works perfectly, but I cannot properly emulate the inertia effect typical of scrollviews.
What I did right now is this:
int beginRawY = 0;
int beginScrollValue = 0;
Integer firstPointerId = null;
[...]
private boolean onTouchEvent(MotionEvent event) {
int index = event.getActionIndex();
int action = event.getActionMasked();
int pointerId = event.getPointerId(index);
int rawY = (int) event.getRawY();
// This is meant to deal with multitouch: scroll only if I'm using "the same finger".
boolean rightPointer = firstPointerId != null && firstPointerId == pointerId;
switch (action) {
case MotionEvent.ACTION_DOWN:
initVelocityTracker(event);
if(firstPointerId == null) {
// Save initial scrollValue and touch position
beginRawY = rawY;
beginScrollValue = scrollValue;
firstPointerId = pointerId;
return true;
}
case MotionEvent.ACTION_MOVE:
if(rightPointer) {
updateVelocity(event);
// Updates scroll value to new scroll value
scrollValue = beginScrollValue -rawY + beginRawY;
return true;
}
case MotionEvent.ACTION_UP:
if(rightPointer) {
//Start the Dissipator runnable, passing to it the speed of the player's touch (number of pixels in 30 milliseconds)
dissipator.setVelocity(updateVelocity(event).pixelY());
dissipator.run();
firstPointerId = null;
return true;
}
}
return false;
}
private void initVelocityTracker(MotionEvent event) {
if(mVelocityTracker == null) {
// Retrieve a new VelocityTracker object to watch the velocity of a motion.
mVelocityTracker = VelocityTracker.obtain();
}
else {
// Reset the velocity tracker back to its initial state.
mVelocityTracker.clear();
}
// Add a user's movement to the tracker.
mVelocityTracker.addMovement(event);
}
private PixelDot updateVelocity(MotionEvent event) {
int pointerId = event.getPointerId(event.getActionIndex());
mVelocityTracker.addMovement(event);
mVelocityTracker.computeCurrentVelocity(30);
return new PixelDot(
VelocityTrackerCompat.getXVelocity(mVelocityTracker, pointerId),
VelocityTrackerCompat.getYVelocity(mVelocityTracker, pointerId));
}
[...]
private class DissipatorRunnable implements Runnable {
private float velocity = 0;
public void setVelocity(float velocity) {
this.velocity = velocity;
}
#Override
public void run() {
// Simply linear descreasing of the scroll speed
float vValue = velocity;
if(velocity > 0) {
while (vValue > 0 && scrollValue > 0) {
scrollValue = scrollValue - vValue;
vValue -= 5;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
while (vValue < 0 && scrollValue < height) {
scrollValue = scrollValue - vValue;
vValue += 5;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Code is simplier than it looks:
I use a ScrollValue to represent "how much the player scrolled". It is the number of pixels.
On Touch Down a save th eposition of the finger and the actual scrollvalue. I initialize a VelocityTracker too.
On Touch Move I update the velocity tracker and the scrollvalue.
On Touch Up I start a custom Runnable called Dissipator:
Every tot milliseconds I reduce (or increment) scrollvalue by the last tracked velocity, and then reduce the velocity value.
This kinda works, but the effect doesn't look like a scrollview with proper inertia, inertia is instead silly and too strong.
What should I do to emulate standard scrollviews inertia?
I'm trying to implement four custom shaped buttons like you can see in the following picture:
What I did so far: I took 4 different pictures - each with only one color visible (see above). The other part of the image is transparent. This has the result, that I have four pictures with the same size.
Now I used a relative-layout where all my 4 pictures are added into imageviews on the same position. Because of the transparency, I can see the desired picture.
For my ImageViews I've implemented onTouchListener with the following content:
private class ImageOnTouchListener implements View.OnTouchListener {
private int categoryId;
public ImageOnTouchListener(int categoryId) {
this.categoryId = categoryId;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
int x = (int) event.getX();
int y = (int) event.getY();
boolean isInsideBitmap = x < bmp.getWidth() && y < bmp.getHeight() && x >= 0 && y >= 0;
boolean isActionUp = event.getAction() == MotionEvent.ACTION_UP;
if (isInsideBitmap) {
int color = bmp.getPixel(x, y);
bmp.recycle();
if (color == Color.TRANSPARENT){
return false;
}
else {
if (isActionUp) {
buttonClick();
}
}
}else{
bmp.recycle();
}
return true;
}
}
This approach works but it consumes a lot of memory as I'm always creating a bitmap when I move my finger. I'm not quite sure if this is the best way to implement this. Is there anything I can do different which might result in a more efficient way?
Using the fact that you can tell whether or not coordinates belong in a circle with the equation x² + y² <= radius² when the circle's center is (0, 0), I think the following should work.
public class ImageOnTouchListener implements View.OnTouchListener {
// TODO Adjust this value
private static int QUADRANT_RADIUS = 100; // in pixels
// TODO Adjust this value
private static int SPACE_BETWEEN_QUADRANTS = 5; // in pixels
#Override
public boolean onTouch(View v, MotionEvent event) {
int relativeX = (int) (event.getX() - v.getX());
int relativeY = (int) (event.getY() - v.getY());
int center = QUADRANT_RADIUS + (SPACE_BETWEEN_QUADRANTS / 2);
boolean isInsideCircle = Math.pow(relativeX - center, 2) + Math.pow(relativeY - center, 2) <= Math.pow(center, 2);
boolean isInsideBottomLeftQuadrant = isInsideCircle &&
relativeX <= QUADRANT_RADIUS &&
relativeY >= QUADRANT_RADIUS + SPACE_BETWEEN_QUADRANTS;
boolean isInsideBottomRightQuadrant = isInsideCircle &&
relativeX >= QUADRANT_RADIUS + SPACE_BETWEEN_QUADRANTS &&
relativeY >= QUADRANT_RADIUS + SPACE_BETWEEN_QUADRANTS;
boolean isInsideTopLeftQuadrant = isInsideCircle &&
relativeX <= QUADRANT_RADIUS &&
relativeY <= QUADRANT_RADIUS;
boolean isInsideTopRightQuadrant = isInsideCircle &&
relativeX >= QUADRANT_RADIUS + SPACE_BETWEEN_QUADRANTS &&
relativeY <= QUADRANT_RADIUS;
boolean isActionUp = event.getAction() == MotionEvent.ACTION_UP;
if (isActionUp) {
if (isInsideBottomLeftQuadrant) {
// Handle bottom left quadrant click
buttonClick();
return true;
} else if (isInsideBottomRightQuadrant) {
// Handle bottom right quadrant click
} // etc.
}
return false;
}
}
You'll need to adjust the QUADRANT_RADIUS and SPACE_BETWEEN_QUADRANTS values, and then either handle all touch events from a single view (like my snippet does) or have a slightly different touch listener per image.
I'm doing a simple match-three game, similar to Bejeweled and I just want to move sprite objects by touching the sprite object and then move it one step in four directions like left, right, up and down. I do this by comparing the X and Y values on Down with the X and Y values on Move. It's working but it's far from perfect! It's so easy to get a wrong value if the movement isn't straight. My questions is: is there a way to improve this and make it better?
I have also looked at gesture, but this seems very complicated to use with a surfaceview that I have.
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("test","Down");
touchActionDownX = (int)event.getX();
touchActionDownY = (int)event.getY();
touchActionMoveStatus = true;
gameLoop.touchX = (int)event.getX();
gameLoop.touchY = (int)event.getY();
gameLoop.touchActionDown = true;
break;
case MotionEvent.ACTION_POINTER_UP:
touchActionMoveStatus = true;
break;
case MotionEvent.ACTION_MOVE:
//Log.i("test","Move");
gameLoop.touchActionMove = true;
if(touchActionMoveStatus) {
touchActionMoveX = (int)event.getX();
touchActionMoveY = (int)event.getY();
if(touchActionMoveX < touchActionDownX)
Log.i("test","Move Left");
else if(touchActionMoveX > touchActionDownX)
Log.i("test","Move Right");
else if(touchActionMoveY < touchActionDownY)
Log.i("test","Move Up");
else if(touchActionMoveY > touchActionDownY)
Log.i("test","Move Down");
touchActionMoveStatus = false; // Will be set to true when pointer is up
}
break;
}
// return false;
return true; // This gets the coordinates all the time
}
Try something like this:
#Override
public boolean onTouch(View v, MotionEvent event) {
//You may have to play with the value and make it density dependant.
int threshold = 10;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("test","Down");
touchActionDownX = (int)event.getX();
touchActionDownY = (int)event.getY();
touchActionMoveStatus = true;
gameLoop.touchX = (int)event.getX();
gameLoop.touchY = (int)event.getY();
gameLoop.touchActionDown = true;
break;
case MotionEvent.ACTION_POINTER_UP:
touchActionMoveStatus = false;
break;
case MotionEvent.ACTION_MOVE:
//Log.i("test","Move");
gameLoop.touchActionMove = true;
if(touchActionMoveStatus) {
touchActionMoveX = (int)event.getX();
touchActionMoveY = (int)event.getY();
if(touchActionMoveX < (touchActionDownX - threshold) && (touchActionMoveY > (touchActionDownY - threshold)) && (touchActionMoveY (touchActionDownY + threshold))){
Log.i("test","Move Left");//If the move left was greater than the threshold and not greater than the threshold up or down
touchActionMoveStatus = false;
}
else if(touchActionMoveX > (touchActionDownX + threshold) && (touchActionMoveY > (touchActionDownY - threshold)) && (touchActionMoveY < (touchActionDownY + threshold))){
Log.i("test","Move Right");//If the move right was greater than the threshold and not greater than the threshold up or
touchActionMoveStatus = false;
}
else if(touchActionMoveY < (touchActionDownY - threshold) && (touchActionMoveX > (touchActionDownX - threshold)) && (touchActionMoveX < (touchActionDownX + threshold))){
Log.i("test","Move Up");//If the move up was greater than the threshold and not greater than the threshold left or right
touchActionMoveStatus = false;
}
else if(touchActionMoveY > (touchActionDownY + threshold) && (touchActionMoveX > (touchActionDownX - threshold)) && (touchActionMoveX < (touchActionDownX + threshold))){
Log.i("test","Move Down");//If the move down was greater than the threshold and not greater than the threshold left or right
touchActionMoveStatus = false;
}
}
break;
}
// return false;
return true; // This gets the coordinates all the time
}
Or use a ratio:
#Override
public boolean onTouch(View v, MotionEvent event) {
//You may have to play with the value.
//A value of two means you require the user to move twice as
//far in the direction they intend to move than any perpendicular direction.
float threshold = 2.0;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("test","Down");
touchActionDownX = (int)event.getX();
touchActionDownY = (int)event.getY();
touchActionMoveStatus = true;
gameLoop.touchX = (int)event.getX();
gameLoop.touchY = (int)event.getY();
gameLoop.touchActionDown = true;
break;
case MotionEvent.ACTION_POINTER_UP:
touchActionMoveStatus = true;
break;
case MotionEvent.ACTION_MOVE:
//Log.i("test","Move");
gameLoop.touchActionMove = true;
if(touchActionMoveStatus) {
touchActionMoveX = (int)event.getX();
touchActionMoveY = (int)event.getY();
// I haven't tested this so you may have a few typos to correct.
float ratioLeftRight = Math.abs(touchActionMoveX - touchActionDownX)/Math.abs(touchActionMoveY - touchActionDownY)
float ratioUpDown = Math.abs(touchActionMoveY - touchActionDownY)/Math.abs(touchActionMoveX - touchActionDownX)
if(touchActionMoveX < touchActionDownX && ratioLeftRight > threshold){
Log.i("test","Move Left");
touchActionMoveStatus = false;
}
else if(touchActionMoveX > touchActionDownX && ratioLeftRight > threshold){
Log.i("test","Move Right");
touchActionMoveStatus = false;
}
else if(touchActionMoveY < touchActionDownY && ratioUpDown > threshold){
Log.i("test","Move Up");
touchActionMoveStatus = false;
}
else if(touchActionMoveY > touchActionDownY && ratioUpDown > threshold){
Log.i("test","Move Down");
touchActionMoveStatus = false;
}
}
break;
}
// return false;
return true; // This gets the coordinates all the time
}
I would choose the dimension with the LARGEST movement and completely ignore the other, for example if the move is x=10 and y=8 then only use the x dimension (i.e. left/right) and vice versa.
Also as noted by Larry McKenzie, using a threshold to ignore smaller movements is a good idea to prevent registering accidental movements that the user did not intend. Tweak the threshold value to someting that feels natural.
Here is some code using your example (only the ACTION_MOVE case):
case MotionEvent.ACTION_MOVE:
//Log.i("test","Move");
gameLoop.touchActionMove = true;
if(touchActionMoveStatus) {
touchActionMoveX = (int)event.getX();
touchActionMoveY = (int)event.getY();
// setup a threshold (below which no movement would occur)
int threshold = 5; /* tweak this as needed */
// first calculate the "delta" movement amounts
int xMove = touchActionMoveX - touchActionDownX;
int yMove = touchActionMoveY - touchActionDownY;
// now find the largest of the two (note that if they
// are equal, x is assumed largest)
if ( Math.abs( xMove ) >= Math.abs( yMove ) ) { /* X-Axis */
if ( xMove >= threshold )
Log.i("test","Move Right");
else if ( xMove <= -threshold )
Log.i("test","Move Left");
}
else { /* Y-Axis */
if ( yMove >= threshold )
Log.i("test","Move Down");
else if ( yMove <= -threshold )
Log.i("test","Move Up");
}
touchActionMoveStatus = false; // Will be set to true when pointer is up
}
}
break;
NOTE: As mentioned in some of the other answers, because multiple events with very small values can occur, it might be best to accumulate (i.e. sum up) the movements UNTIL the threshold is reached - you can use members for this that reset in ACTION_DOWN. Once the threshold is reached (in either dimension) THEN you can perform the checks for which direction.
Alternative Approach
Another way to go about it would be to detect the largest movement in the FIRST ACTION_MOVE event, and then lock all further movements to that dimension. For this you would need to add various state members - these would need to be updated in each state.
Here is a rough example (with only the state tracking):
// members
private boolean axisLock = false; /* Track When Lock is Required */
private boolean axisX = true; /* Axis to Lock (true) for X, (false) for Y */
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// set this state so that ACTION_MOVE knows a lock is required
axisLock = true;
break;
case MotionEvent.ACTION_UP:
// clear the state in case no move was made
axisLock = false;
case MotionEvent.ACTION_MOVE:
// now lock the axis if this is the first move event
if ( axisLock ) {
// this will set whether the locked axis is X (true) or Y (false)
axisX = event.getX() >= event.getY();
// reset the state (to keep the axis locked)
axisLock = false;
}
// at this point you only need to consider the movement for the locked axis
if ( axisX ) {
int movement = (int)event.getX(); /* Get Movement for Locked Axis */
// check for your movement conditions here
}
else {
int movement = (int)event.getY(); /* Get Movement for Locked Axis */
// check for your movement conditions here
}
break;
}
return true;
}
You could add many optimizations to this code, for now it just illustrates the basic idea.
larry had the right idea, i just want to put in a lil fix,
//put this in the wraping class
private static int THRESHOLD = 10;
private static int initX;
private static int initY;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initX = (int)event.getX();
initY = (int)event.getY();
break;
case MotionEvent.ACTION_POINTER_UP:
//you can add in some kind of "move back" animation for the item
break;
case MotionEvent.ACTION_MOVE:
if(((int)event.getY - initY) > THRESHOLD){
//move down
break;
}
if(((int)event.getY - initY) > -THRESHOLD){
//move up
break;
}
if(((int)event.getX - initX) > THRESHOLD){
//move right
break;
}
if(((int)event.getX - initX) < -THRESHOLD){
//move left
break;
}
break;
}
}
i didn't test this code, only free write it, but i hope you get my idea :)
I am working on an algorithm for rotating the camera around a 3D object using the Min3d/Rajawali framework.
With my implementation, the rotation around axis X is not working properly. I think the method setLookAt() is not working properly.
The problem:
When I rotate the sphere vertically, I can't fully see it. For example, turning the planet Earth, I can not fully see the Antarctic, because the algorithm resets the camera down.
Is it possible to realize the camera rotation around an object without using the method "setLookAt"?
I have tried different solutions, but have not been able to get it working correctly.
Below is my code:
initScene:
scene.camera().position.z = 90;
scene.camera().target = raketeOBJ.position();
onTouchEvent:
public boolean onTouchEvent(MotionEvent me) {
if (me.getAction() == MotionEvent.ACTION_DOWN) {
xpos = me.getX();
ypos = me.getY();
return true;
}
if (me.getAction() == MotionEvent.ACTION_UP) {
xpos = -1;
ypos = -1;
touchTurn = 0;
touchTurnUp = 0;
return true;
}
if (me.getAction() == MotionEvent.ACTION_MOVE) {
float xd = me.getX() - xpos;
float yd = me.getY() - ypos;
xpos = me.getX();
ypos = me.getY();
touchTurn = xd / -200f;
touchTurnUp = yd / -200f;
return true;
}
try {
Thread.sleep(15);
} catch (Exception e) {
}
return super.onTouchEvent(me);
}
UpdateScene:
if (touchTurn != 0) {
scene.camera().position.rotateY(touchTurn);
touchTurn = 0;
}
if (touchTurnUp != 0) {
scene.camera().position.rotateX(touchTurnUp);
touchTurnUp = 0;
}
Number3d target = scene.camera.target;
Number3d cp = scene.camera.position.clone();
// move position like target is (0,0,0)
cp.x -= target.x;
cp.y -= target.y;
cp.z -= target.z;
cp.roateX(angle);
// restore offset
cp.x += target.x;
cp.y += target.y;
cp.z += target.z;
scene.camera.position.setAllFrom(cp);
A bit late but in case anyone has trouble with that, like me.
Rajawali offers a camera called ArcballCamera, which does exactly what you/we are trying to do.
In your Renderer add the following:
ArcballCamera arcball = new ArcballCamera(mContext, ((Activity)mContext).findViewById(R.id.contentView));
arcball.setTarget(mObjectGroup); //your 3D Object
arcball.setPosition(0,0,4); //optional
getCurrentScene().replaceAndSwitchCamera(getCurrentCamera(), arcball);
now you can rotate and zoom the object without a dozen lines of code.
setLookAt() needs to be called onDrawFrame if you want the camera to update regularly. But you need to care more about creating a "RotateAroundAnimation". See here for more info: http://www.rozengain.com/blog/2012/03/26/rajawali-tutorial-12-animation-classes/
You'll have to make yourAnimation.setTransformable3D(mCamera), and then it should control your main camera. I often use this methodology and then call the "yourAnimation.start()" on touch, or other external stimulus.
This is my way to rotate 3d model according as x and y
in Render class
public boolean left, right;
public boolean up, down;
and in onDrawFrame
#Override
public void onDrawFrame(GL10 glUnused) {
super.onDrawFrame(glUnused);
// getCurrentCamera().setRotY(getCurrentCamera().getRotY() + 1);
if (left) {
getCurrentCamera().setRotX(getCurrentCamera().getRotX() - 1);
}
if (right) {
getCurrentCamera().setRotX(getCurrentCamera().getRotX() + 1);
}
if (up) {
getCurrentCamera().setRotY(getCurrentCamera().getRotY() - 1);
}
if (down) {
getCurrentCamera().setRotY(getCurrentCamera().getRotY() + 1);
}
}
and in MainActivity
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
xpos = event.getX();
ypos = event.getY();
}
if (event.getAction() == MotionEvent.ACTION_UP) {
xpos = -1;
ypos = -1;
mRender.left = false;
mRender.right = false;
mRender.up = false;
mRender.down = false;
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
xd = event.getX() - xpos;
yd = event.getY() - ypos;
xpos = event.getX();
ypos = event.getY();
if (xd < 0) {
mRender.up = true;
} else {
mRender.down = true;
}
if (yd < 0) {
mRender.left = true;
} else {
mRender.right = true;
}
}
return super.onTouchEvent(event);
}
by this way, i can rotate my model :)
I have a custom View with bitmaps on it that the user can drag about.
I want to make it so when they long click one of them I can pop up a context menu with options such as reset position etc.
In the custom View I add my OnLongClickListener:
this.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// show context menu..
return true;
}
});
And override onTouchEvent to look something like this:
public boolean onTouchEvent(MotionEvent event) {
handleDrag(event);
super.onTouchEvent(event);
return true;
}
The handleDrag function finds what object is been pressed, and handles updating it's position.
My problem is that when I start to drag an image the OnLongClickListener fires also. I'm not sure the best way around this.
I've tried adding a threshold to handleDrag to return false if user touches down but doesn't attempt to drag, but I'm finding it still difficult to get the correct handler fired.
Can anyone suggest a way to skip the OnLongClickListener while dragging?
I think I have this solved through tweaking my threshold approach.
First, I changed my onTouchEvent to look like this:
public boolean onTouchEvent(MotionEvent event) {
mMultiTouchController.handleDrag(event);
return super.onTouchEvent(event);
}
They now both fire, so I then changed my OnLongClickListener to the following:
this.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (!mMultiTouchController.has_moved) {
// Pop menu and done...
return false;
}
return true;
}
});
(mMultiTouchController is the class containing all my gesture detection code).
The key here is within this class, I added the bool 'has_moved'. When I go to start a drag I then compute the delta:
float diffX = Math.abs(mCurrPtX - mPrevPt.getX());
float diffY = Math.abs(mCurrPtY - mPrevPt.getY());
if (diffX < threshold && diffY < threshold) {
has_moved = false;
return;
}
Now when the onLongClick fires I know whether to take action or not.
The final piece was to set:
setHapticFeedbackEnabled(false);
in my View so that the user doesn't get a vibrate every time the longClick fires but no action is taken. I plan to do the vibration manually as a next step.
This seems to be ok so far, hope that helps anyone who has come across a similar situation as this one.
I would stop using the onLongClickListener and just implement your own, which is pretty easy to do. Then you have the control you need to keep them from interfering with each other.
The following code implements the following gestures: drag, tap, double tap, long click, and pinch.
static final short NONE = 0;
static final short DRAG = 1;
static final short ZOOM = 2;
static final short TAP = 3;
static final short DOUBLE_TAP = 4;
static final short POST_GESTURE = 5;
short mode = NONE;
static final float MIN_PINCH_DISTANCE = 30f;
static final float MIN_DRAG_DISTANCE = 5f;
static final float DOUBLE_TAP_MAX_DISTANCE = 30f;
static final long MAX_DOUBLE_TAP_MS = 1000;
static final long LONG_PRESS_THRESHOLD_MS = 2000;
public class Vector2d {
public float x;
public float y;
public Vector2d() {
x = 0f;
y = 0f;
}
public void set(float newX, float newY) {
x = newX;
y = newY;
}
public Vector2d avgVector(Vector2d remote) {
Vector2d mid = new Vector2d();
mid.set((remote.x + x)/2, (remote.y + y)/2);
return mid;
}
public float length() {
return (float) Math.sqrt(x * x + y * y);
}
public float distance(Vector2d remote) {
float deltaX = remote.x - x;
float deltaY = remote.y - y;
return (float) Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}
}
private Vector2d finger1 = new Vector2d();
private Vector2d finger2 = new Vector2d();
private Vector2d pinchStartDistance = new Vector2d();
private Vector2d pinchMidPoint;
private Vector2d fingerStartPoint = new Vector2d();
private long gestureStartTime;
private Marker selectedMarker;
#Override
public boolean onTouch(View v, MotionEvent event) {
// Dump touch event to log
dumpEvent(event);
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
finger1.set(event.getX(), event.getY());
if (mode == TAP) {
if (finger1.distance(fingerStartPoint) < DOUBLE_TAP_MAX_DISTANCE) {
mode = DOUBLE_TAP;
} else {
mode = NONE;
gestureStartTime = SystemClock.uptimeMillis();
}
} else {
gestureStartTime = SystemClock.uptimeMillis();
}
fingerStartPoint.set(event.getX(), event.getY());
break;
case MotionEvent.ACTION_POINTER_DOWN:
finger2.set(event.getX(1), event.getY(1));
pinchStartDistance.set(Math.abs(finger1.x - finger2.x), Math.abs(finger1.y - finger2.y));
Log.d(TAG, String.format("pinch start distance = %f, %f", pinchStartDistance.x, pinchStartDistance.y));
if (pinchStartDistance.length() > MIN_PINCH_DISTANCE) {
if (pinchStartDistance.x < MIN_PINCH_DISTANCE) {
pinchStartDistance.x = MIN_PINCH_DISTANCE;
}
if (pinchStartDistance.y < MIN_PINCH_DISTANCE) {
pinchStartDistance.y = MIN_PINCH_DISTANCE;
}
pinchMidPoint = finger1.avgVector(finger2);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM" );
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
if (mode == ZOOM) {
Vector2d pinchEndDistance = new Vector2d();
pinchEndDistance.set(Math.abs(finger1.x - finger2.x), Math.abs(finger1.y - finger2.y));
if (pinchEndDistance.x < MIN_PINCH_DISTANCE) {
pinchEndDistance.x = MIN_PINCH_DISTANCE;
}
if (pinchEndDistance.y < MIN_PINCH_DISTANCE) {
pinchEndDistance.y = MIN_PINCH_DISTANCE;
}
Log.d(TAG, String.format("pinch end distance = %f, %f", pinchEndDistance.x, pinchEndDistance.y));
zoom(pinchMidPoint, pinchStartDistance.x/pinchEndDistance.x, pinchStartDistance.y/pinchEndDistance.y);
// Set mode to "POST_GESTURE" so that when the other finger lifts the handler won't think it was a
// tap or something.
mode = POST_GESTURE;
} else if (mode == NONE) {
// The finger wasn't moved enough for it to be considered a "drag", so it is either a tap
// or a "long press", depending on how long it was down.
if ((SystemClock.uptimeMillis() - gestureStartTime) < LONG_PRESS_THRESHOLD_MS) {
Log.d(TAG, "mode=TAP");
mode = TAP;
selectedMarker = checkForMarker(finger1);
if (selectedMarker != null) {
Log.d(TAG, "Selected marker, mode=NONE");
mode = NONE;
((Activity) parent).showDialog(ResultsActivity.DIALOG_MARKER_ID);
}
}
else {
Log.d(TAG, "mode=LONG_PRESS");
addMarker(finger1);
requestRender();
}
} else if (mode == DOUBLE_TAP && (SystemClock.uptimeMillis() - gestureStartTime) < MAX_DOUBLE_TAP_MS) {
// The finger was again not moved enough for it to be considered a "drag", so it is
// a double-tap. Change the center point and zoom in.
Log.d(TAG, "mode=DOUBLE_TAP");
zoom(fingerStartPoint, 0.5f, 0.5f);
mode = NONE;
} else {
mode = NONE;
Log.d(TAG, "mode=NONE" );
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == NONE || mode == TAP || mode == DOUBLE_TAP) {
finger1.set(event.getX(), event.getY());
if (finger1.distance(fingerStartPoint) > MIN_DRAG_DISTANCE) {
Log.d(TAG, "mode=DRAG" );
mode = DRAG;
scroll(fingerStartPoint.x - finger1.x, fingerStartPoint.y - finger1.y);
}
}
else if (mode == DRAG) {
scroll(finger1.x - event.getX(), finger1.y - event.getY());
finger1.set(event.getX(), event.getY());
}
else if (mode == ZOOM) {
for (int i=0; i<event.getPointerCount(); i++) {
if (event.getPointerId(i) == 0) {
finger1.set(event.getX(i), event.getY(i));
}
else if (event.getPointerId(i) == 1) {
finger2.set(event.getX(i), event.getY(i));
}
else {
Log.w(TAG, String.format("Unknown motion event pointer id: %d", event.getPointerId(i)));
}
}
}
break;
}
return true;
}
/** Show an event in the LogCat view, for debugging */
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" ,
"POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_" ).append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid " ).append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")" );
}
sb.append("[" );
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#" ).append(i);
sb.append("(pid " ).append(event.getPointerId(i));
sb.append(")=" ).append((int) event.getX(i));
sb.append("," ).append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";" );
}
sb.append("]" );
Log.d(TAG, sb.toString());
}
//This code is to handle the gestures detection
final Handler handler = new Handler();
private Runnable mLongPressRunnable;
detector = new GestureDetector(this, new MyGestureDectector());
view.setOnTouchListener(new OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#SuppressWarnings("deprecation")
#Override
public boolean onTouch(View v, MotionEvent event) {
detector.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
handler.postDelayed(mLongPressRunnable, 1000);
}
if ((event.getAction() == MotionEvent.ACTION_MOVE)
|| (event.getAction() == MotionEvent.ACTION_UP)) {
handler.removeCallbacks(mLongPressRunnable);
}
}
return true;
}
});
mLongPressRunnable = new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "long", Toast.LENGTH_SHORT)
.show();
}
};
class MyGestureDectector implements GestureDetector.OnDoubleTapListener,
OnGestureListener {
//Implement all the methods
}