~经言/歌词~

I find that the harder I work, the more luck I seem to have.
~ Thomas Jefferson (1743-1826)

Wednesday, November 16, 2011

Android: Flipping Gestures Activity

Flipping feature, I guess that is a feature that is inevitable to all touch screen apps. It is very cool to see the pages changed just by a fling, buttons no longer required. Sometimes, buttons could be very tedious!!!

As for android programming, in order to perform the flipping gesture, the best way of doing it is to include the OnGestureListener. However, be aware of the library to be imported, there are two libraries contain this listener with different implementation, which is the android.view.GestureDetector and android.gesture.GestureOverlayView. You should import android.view.GestureDetector in the project.

Since OnGestureListener is a interface class, there are several functions you need to include into your project, whether you like it or not.
  • boolean onDown(MotionEvent e) 
  • boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
  • void onLongPress(MotionEvent e)
  • boolean onScoll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
  • boolean onShowPress(MotionEvent e)
  • boolean onSingleTapUp(MotionEvent e)
Since this post is working with the flipping feature, we will only work with onFling function.

First of all, starts with a simple layout.


As you can see from the layout above, a new component, ViewFlipper is included into the xml declaration file. ViewFlipper is working as a flipper that contains the multiple views of your design. From the layout above, I created three TextView where each represent different pages when I fling my apps later. 


As usual, declare a ViewFlipper instance in the main file.


After that, in the onFling() function, add the code below,

velocityX is indicating the x-axis coordination when you fling, if you fling to the left, velocityX is less than 0, therefore it will show the previous page, it shows the next page otherwise.



android.R.anim.fade_in and android.R.anim.fade_out are animation moves that provided by android itself. These animations help to show an animation movement when we fling the pages. Refers here for more animation movements.

If we only included the codes above, it wasnt done yet! The codes above are written for the when a fling gesture detected. However, how did a touch screen device detect the fling or scroll, or other gesture activities? 

In android programming, we need to declare GestureDetector instance to detect the gestures that were applied to the screens. Includes the codes in the red boxes into the onCreate() and creates new function onTouchEvent(). 


That's it!!! You can now fling your apps!!!


2 comments:

Catherine said...

Ok, new thing for me!

Nice explanation ^^

维整 said...

haha, thanks cat!!!