블로그 이미지
박황기
최근에 스마트폰에 관심이 많습니다. 예전에 상상하던 모습들이 점차 이루어지고 있는게 신기하네요.

calendar

1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

Notice

2010. 9. 23. 20:11 모바일/안드로이드

출처(source) : http://www.codeshogun.com/blog/2009/04/16/how-to-implement-swipe-action-in-android/


To implement swipe action in Android, such as the one used in iPhone homescreen unlock, actually Android SDK provides native support for gestures. Swipe is actually called Fling ^_^

You will need to extend SimpleOnGestureListener to implement your own handling on swipe/fling action:

class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
}

To determine if it’s a valid swipe, you will need to make sure the fling falls into an almost straight path, with at least certain length of touch duration, so it’s a continuous touch, and with certain velocity of course.

So let’s define some constants:

private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;

The max off path is to make sure the fling still falls within a somewhat straight path.

If onFling() method, you can do this:

if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
viewFlipper.setInAnimation(slideLeftIn);
viewFlipper.setOutAnimation(slideLeftOut);
viewFlipper.showNext();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
viewFlipper.setInAnimation(slideRightIn);
viewFlipper.setOutAnimation(slideRightOut);
viewFlipper.showPrevious();
}

The viewFlipper is used to show how fling/swipe make the view animation/transition from one to the other.

At last, you need to make sure in your activity, you catch the gesture event by overriding onTouch() method:

@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}

Here’s a screenshot of the view in transition:

Android Swipe View Flipper in Action

Android Swipe View Flipper in Action

The sample source is attached here.

'모바일 > 안드로이드' 카테고리의 다른 글

Syntax Diagrams For SQLite  (0) 2010.09.30
Audio Capture  (0) 2010.09.24
how to make mp4 for streaming  (0) 2010.07.13
안드로이드 UI  (0) 2010.07.13
Play MediaPlayer with Authentication on Android  (0) 2010.07.08
posted by 박황기