Saturday, December 14, 2013

Android: Insert Animations

In today's post I want to describe, how to get some movement in your apps by using animations.
When programming for Android, there are basically 3 possibilites: There are View Animations, Drawable Animations and Property Animations. In this post I only want to cover the last class, which was introduced last (in Android 3.0) and therefor also provides the most possibilites and is generally used.
Of Property Animations there are again 3 subclasses: ValueAnimator, ObjectAnimator and AnimationSet. AnimatorSet is used for connecting animations, I will dedicate an own post to this class soon.
With the ValueAnimator arbitrary values can be changed over time. In this post though I will only describe the usage of the subclass ObjectAnimator, which was particularly designed for animating objects, which should be sufficient for most applications.
Now directly to the code. In the example we create a LinearLayout, in which a TextView and a Button are aligned below each other, and in which the TextView is moved to the right via an animation when the Button is clicked.
For animations we need the namespace Android.Animation, which we include via using. Then we create the Animator from the class ObjectAnimator and choose, whether we want to change an integer or float value. To this creation method we pass over the name of the object we want to animate, the name of the target value as a string, as well as start and end value. The following lines change the property Left of the object TxtView1 from 0 to 100, thus moving the object to the right. In the second line we set the duration of the animation, and in the third we eventually start it:

ObjectAnimator Animator = ObjectAnimator.OfInt(TxtView1, "Left", 0, 100);

The complete code is:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

using Android.Animation;

namespace AnimationsExample
     [Activity (Label = "AnimationsExample", MainLauncher = true)]
     public class MainActivity : Activity
          protected override void OnCreate (Bundle bundle)
               base.OnCreate (bundle);

               LinearLayout Layout = new LinearLayout (this);
               Layout.Orientation = Orientation.Vertical;

               TextView TxtView1 = new TextView (this);
               TxtView1.Text = "I'm flying";
               Layout.AddView (TxtView1);

               Button Btn1 = new Button (this);
               Btn1.Text = "Animation";
               Layout.AddView (Btn1);

               Btn1.Click += (object sender, EventArgs e) => {
                    ObjectAnimator Animator = ObjectAnimator.OfInt(TxtView1, "Left", 0, 100);

               SetContentView (Layout);

No comments:

Post a Comment