Tuesday, June 3, 2014

Custom Swipe Action

Project : The Path Game

Requirement:  Implement swipe (up,down,left & right) action on the a specific layout.
When users swipes on the layout(in red) the header tile moves in the direction of swipe.

Solution:
Create a View.OnTouchListener set it as the on touch listener for the required layout.
View.OnTouchListener gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = event.getX(); //get x-point of finger down
y1 = event.getY(); //get y-point of finger down
break;
case MotionEvent.ACTION_UP:
x2 = event.getX(); //get x-point of finger up
y2 = event.getY(); //get x-point of finger up
dy = y2 - y1; //y distance of swipe
dx = x2 - x1; //x distance of swipe
absDX = Math.abs(dx);
absDY = Math.abs(dy);
if(absDX < SWIPE_MIN_DISTANCE && absDY < SWIPE_MIN_DISTANCE){
// y and x distance of swipe should be greater than a minimum value
}else{
if(absDX >= absDY){
if(dx > 0){
moveRight();
}else{
moveLeft();
}
}else{
if(dy > 0){
moveDown();
}else{
moveUp();
}
}
}
break;
}
return true;
}
};
view raw custom_swipe hosted with ❤ by GitHub

No comments:

Post a Comment