I have an imageView & I want to find out in which direction the touch is moving. On DOWN, it stores the X and Y coordinates in variables initX and initY. On move, it stores the current coordinates on finalX and finalY.
I have these variables displayed in textViews, and they're showing the values I'd expect.
On UP, I call another method, whichWayToMove, and pass it initX, initY, finalX and finalY. However, the values passed through are always zero. They shouldn't be. Any idea why?
public void moveTile(){
ImageView view1 = (ImageView) findViewById(R.id.view1);
ImageView view2 = (ImageView) findViewById(R.id.view2);
final TextView tv = (TextView) findViewById(R.id.textView);
final TextView tv2 = (TextView) findViewById(R.id.textView2);
final TextView tv3 = (TextView) findViewById(R.id.textView3);
view1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) { // half-inched from https://developer.android.com/training/gestures/detector.html
int initialY =0;
int finalY = 0;
int initialX = 0;
int finalX = 0;
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN):
initialX = (int) event.getX();
initialY = (int) event.getY();
tv.setText(initialX + ", " + initialY);
tv3.setText( initialX + ", " + initialY );
return true;
case (MotionEvent.ACTION_MOVE):
tv.setText("Action was MOVE");
finalX = (int) event.getX();
finalY = (int) event.getY();
tv2.setText(finalX + ", " + finalY);
return true;
case (MotionEvent.ACTION_UP):
whichWayToMove(initialX, finalX, initialY, finalY);
tv.setText("Action was UP");
return true;
case (MotionEvent.ACTION_CANCEL):
tv.setText("Action was CANCEL");
return true;
case (MotionEvent.ACTION_OUTSIDE):
tv.setText("Movement occurred outside bounds " +
"of current screen element");
return true;
default:
tv.setText("wut?");
}
return false;
}
});
}
public void whichWayToMove(int initX, int finalX, int initY, int finalY){
TextView tv4 = (TextView) findViewById(R.id.textView4);
TextView tv5 = (TextView) findViewById(R.id.textView5);
tv5.setText("initX: " + initX + ". finalX: " + finalX + " initY: " + initY + " . finalY: " +
"" + finalY +
"" );
String direction = "";
int deltaX = initX - finalX;
int deltaY = initY - finalY;
if (Math.abs(deltaX)> Math.abs(deltaY)){ // then we're moving on the X axis
if (deltaX >= 0){direction = "left";}
else {direction = "right";}
}
else { // we're moving on the Y axis
if (deltaY >= 0){direction = "up";}
else {direction = "down";}
}
// tv4.setText("direction is: " + direction);
tv4.setText("deltaX is: " + deltaX + ". deltaY is: " + deltaY);
}