Android 0nTouch event problem [Swipe DOWN and UP]
im having an application which needs onTouch swipe events like in Iphone. they are
- Swipe Up.
- Swipe Down.
- Swipe Left.
- Swipe Right.
i implemented onTouch event as following . and i got Swipe Left and Right actions correctly.but which is the correct way to implement the swipe Down and Up actions.
MYCODE:
float downXValue,downYValue;
@Override
public boolean onTouchEvent(MotionEvent arg1) {
// Get the action that was done on this touch event
switch (arg1.getAction())
{
case MotionEvent.ACTION_DOWN:
{
// store the X value when the user's finge开发者_运维知识库r was pressed down
downXValue = arg1.getX();
downYValue = arg1.getY();
break;
}
case MotionEvent.ACTION_UP:
{
// Get the X value when the user released his/her finger
float currentX = arg1.getX();
float currentY=arg1.getY();
// going backwards: pushing stuff to the right
if (downXValue < currentX)
{
Log.d(DEBUG_TAG, "Right");
}
// going forwards: pushing stuff to the left
if (downXValue > currentX)
{
Log.d(DEBUG_TAG, "Left");
}
break;
}
}
//GestureListener is called here...
//return gestures.onTouchEvent(event);
return true;
}
Thank you.
What about...
if (downYValue < currentY)
{
Log.d(DEBUG_TAG, "Down");
}
Are you sure you wrote the code above?
Edit
OK, I believe you. What you have to do is basically:
double sizeInX = Math.abs(downXValue - currentX);
double sizeInY = Math.abs(downYValue - currentY);
if( sizeInX > sizeInY ){
// you better swipe horizontally
} else {
// you better swipe vertically
}
This is a listener I wrote some time ago, that handles both up an down swypes. Theres a float oldPosition
variable that I used to track the touch position. There is some unneeded code in there but you'll get the idea:
LinearLayout tableM = (LinearLayout) findViewById (R.id.tableM);
tableM.setOnTouchListener(new OnTouchListener () {
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
oldPosition = event.getY();
return true;
} else
if (event.getAction() == android.view.MotionEvent.ACTION_MOVE) {
if (event.getY() < oldPosition) {
tableIndexM++;
if (tableIndexM > (minsecs.length - 3)) {
tableIndexM = 0;
}
fillTable (rowM0, rowM1, rowM2, minsecs, tableIndexM);
}
else if (event.getY() > oldPosition) {
tableIndexM--;
if (tableIndexM < 0) {
tableIndexM = minsecs.length - 3;
}
fillTable (rowM0, rowM1, rowM2, minsecs, tableIndexM);
}
oldPosition = event.getY();
return true;
}
return false;
}
});
精彩评论