Monday, July 8, 2013

Gesture Listener

1. Create a new Xamarin.Android application namedRecognizeGesture.
2. Edit Main.axml so that its contents match the following:
1 2 3 4 5 6 7 8 9 10 11 12
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:text="Small Text" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/velocity_text_view" /> </LinearLayout>
3. Edit MainActivity.cs, and add the following instance variable to the class:
1
private GestureDetector _gestureDetector;
4. Edit MainActivity.cs so  that it implements Android.Views.GestureDetector.IOnGestureListener and the methods required by that interface. More functionality will be added to the OnFling method further on in step .:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public class Activity1 : Activity, GestureDetector.IOnGestureListener { public bool OnDown(MotionEvent e) { } public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { } public void OnLongPress(MotionEvent e) {} public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { } public void OnShowPress(MotionEvent e) {} public bool OnSingleTapUp(MotionEvent e) { return false; } }
5. Edit the OnFling method so that it will display some values captured when the user “flings” on the screen:
1 2 3 4 5
public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { _textView.Text = String.Format("Fling velocity: {0} x {1}", velocityX, velocityY); return true; }
6. Create an instance of GestureDetector for the Activity. Modify OnCreate as shown in the following snippet:
1 2 3 4 5 6 7 8
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); _textView = FindViewById<TextView>(Resource.Id.velocity_text_view); _textView.Text = "Fling Velocity: "; _gestureDetector = new GestureDetector(this); }
7. Override the method OnTouchEvent in the Activity. This will delegate the handling of the gesture to theGestureDetector.IOnGestureListener methods implemented by the class.
1 2 3 4 5
public override bool OnTouchEvent(MotionEvent e) { _gestureDetector.OnTouchEvent(e); return false; }
8. Run the application on a device, and fling your finger across the screen. You will see the X and Y velocities change:

No comments:

Post a Comment