Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Android Gesture Recognition and Animation with Xamarin

DZone's Guide to

Android Gesture Recognition and Animation with Xamarin

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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.


Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}