Search code examples
c#xamarin.android

How to use Value Animator in Xamarin.Android?


I try to use the Value Animator in Xamarin.Android to move an object by increasing its X and Y coordinate. I oriented myself at the Android documentation for Java.

using Android.Support.V4.View;
using Android.Animation;

namespace PaintApp
{
    class PaintView : View
    {
        
        private Pair ofsetXY = new Pair(0, 0);
        private ValueAnimator animator = new ValueAnimator();
        PropertyValuesHolder propertyX = PropertyValuesHolder.OfInt("PROPERTY_X", 0, 1000);
        PropertyValuesHolder propertyY = PropertyValuesHolder.OfInt("PROPERTY_Y", 0, 1000);


        public void Kick(float dx, float dy, float vx, float vy)
        {
            animator.SetValues(propertyX, propertyY);
            animator.SetDuration(2000);
            animator.AddUpdateListener(new ValueAnimator.IAnimatorUpdateListener()
            {
                public override void OnAnimationUpdate(ValueAnimator animation)
                {
                    ofsetXY.First = (int)animation.GetAnimatedValue("PROPERTY_X");
                    ofsetXY.Second = (int)animation.GetAnimatedValue("PROPERTY_Y");
                    Invalidate();
                }
            });
         animator.start();
        }
}

But I get the error: Error CS0144 Cannot create an instance of the abstract class or interface '"ValueAnimator.IAnimatorUpdateListener"' and that OnAnimationUpdate is not a member of PaintView.

This error makes sence to me, but what yould be the correct way?


Solution

  • There are some difference between Java and C# .In your case you could modify the code like following

    class PaintView : Android.Views.View, IAnimatorUpdateListener
    {
        private Pair ofsetXY = new Pair(0, 0);
        private ValueAnimator animator = new ValueAnimator();
        PropertyValuesHolder propertyX = PropertyValuesHolder.OfInt("PROPERTY_X", 0, 1000);
        PropertyValuesHolder propertyY = PropertyValuesHolder.OfInt("PROPERTY_Y", 0, 1000);
    
        public void Kick(float dx, float dy, float vx, float vy)
        {
            animator.SetValues(propertyX, propertyY);
            animator.SetDuration(2000);
            animator.AddUpdateListener(this);
            animator.start();
        }
    
        public void OnAnimationUpdate(ValueAnimator animation)
        {
            ofsetXY.First = (int)animation.GetAnimatedValue("PROPERTY_X");
            ofsetXY.Second = (int)animation.GetAnimatedValue("PROPERTY_Y");
      
            Invalidate();
        }
    }