Over a million developers have joined DZone.

Android Gesture Recognition and Animation with Xamarin

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

In this post we’ll take a look at how to recognize simple and complex touch gestures in an Android application and apply animations to views on screen. Touch gestures are a fundamental way for users to interact with mobile applications, and animations are key to designing a pleasant user experience.

As with all other Xamarin APIs, the native (Java) versions are very similar, so it should be easy to port the examples below to Java if you need to. Let’s get started with recognizing gestures.

Gesture Recognition

Android’s support for touch begins with the onTouchEvent method that every View-derived class can override. This is a fairly low-level API, however, that requires you to deal with touch events directly and doesn’t perform any gesture recognition or processing. The GestureDetector class, on the other hand, is the entry point for detecting gestures without having to deal directly with touch events. For the simplest gestures, such as tap and double-tap, GestureDetector even offers C# events that we can subscribe to. (There is also a ScaleGestureDetector which helps with scaling-specific events, such as pinch to zoom.)

For example, suppose we want to detect a fling gesture that should remove an on-screen element from the screen. We need to initialize the GestureDetector class, subscribe with a listener, pass touch events to the detector, and look for the onFling event callback that notifies us of the event:

public class MainActivity : Activity
{
    private GestureDetector _detector;

    private class GestureListener : GestureDetector.SimpleOnGestureListener
    {
        public override bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
        {
            // TODO
            return true;
        }
    }

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);

        var listener = new GestureListener();
        _detector = new GestureDetector(this, listener);
    }

    protected override bool OnTouchEvent(MotionEvent e)
    {
        _detector.OnTouchEvent(e);
        return base.OnTouchEvent(e);
    }
}

Now, we can detect the fling’s velocity and react accordingly, to remove the view from the screen when it was “flinged off”, e.g. by changing its Visibility property to ViewStates.Gone, or by removing it from its parent container.

Animation

Next, we turn to animations. It would be nice to remove the view from the screen gradually, perhaps fading it out or shifting it off the screen. We can accomplish this and similar effects using the Android animation system, which can animate certain properties of any view. Among the properties that are available for animation we find the alpha (opacity) of a view, its bounds (position), and its rotation.

Animations can be loaded from resource files or created programmatically. In the following example, we’ll create an animation programmatically – it will remove an element off-screen and fade it gradually until it is completely transparent:

var toggleButton = FindViewById<ToggleButton>(Resource.Id.toggle);
var alpha = new AlphaAnimation(1.0f, 0.0f);
var translate = new TranslateAnimation(
    0.0f, (float)WindowManager.DefaultDisplay.Width, 0.0f, 0.0f);
var set = new AnimationSet(shareInterpolator: true);
set.AddAnimation(alpha);
set.AddAnimation(translate);
set.Duration = 2000;
toggleButton.StartAnimation(set);

Newer version of Android have an API that is even easier to use – ViewPropertyAnimator. The following code is equivalent to the example above, but requires API level 12 (Android 3.1 or higher):

toggleButton.Animate()
    .Alpha(0.0f)
    .XBy((float)WindowManager.DefaultDisplay.Width)
    .SetDuration(2000)
    .Start();

Fling gesture to the right makes the view fade out and move off screen

By adding animations and gesture recognizers to your mobile applications, you can make a real difference for your user experience. There is more to gestures and animations than meets the eye, and you’re welcome to explore the official Android documentation for more details.


The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Sasha Goldshtein, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}