Search code examples
c#androidandroid-layoutxamarin.androidandroid-animation

Slide animation between views of a ViewFlipper


In an Activity I have the following:

var flipper = FindViewById<ViewFlipper>(Resource.Id.flipper);
flipper.Touch += flipper_Touch;

The basic implementation of the touch handler looks like this:

float oldTouchValue = 0;

void flipper_Touch(object sender, View.TouchEventArgs e)
{
    var flipper = sender as ViewFlipper;
    switch(e.Event.Action)
    {
        case MotionEventActions.Down:
            oldTouchValue = e.Event.GetX();
            break;

        case MotionEventActions.Up:
            float currentX = e.Event.GetX();
            if (oldTouchValue < currentX)
            {
                flipper.ShowNext();
            }
            else if (oldTouchValue > currentX)
            {
                flipper.ShowPrevious();
            }
            break;      
    }
}

This allows me to navigate between the different views but I'd like to make it slide left/right

I've seen some Java examples on how to make it work, but not direct way to translate it to c#.

What's required to make the views slide and is there a way to define the animation in XML?
I'm able to make Activities slide in and out using animations defined in XML and calls to OverridePendingTransition, but I'm not sure how to apply that knowledge here.


Solution

  • This allows me to navigate between the different views but I'd like to make it slide left/right

    The ViewFlipper has, through its ViewAnimator class, some methods to set the animation for the in and out actions, setInAnimation() and setOutAnimation(). This are in the Android SDK but should have correspondence in MonoDroid(with which unfortunately I'm not familiar so I could be wrong). In order to have the desired animation simply use the two methods above to set the desired animations(either xml file or programmatically built Animation) and then call the showNext/Previous methods like you currently do.

    You even have some slide animation in the Android SDK, but again I don't know if they are present in MonoDroid.

    Update: Those methods are indeed available in Monodroid and exposed like this:

    //Using one of the built in animations:
    flipper.setInAnimation(this, Android.Resource.Animation.SlideInLeft);
    flipper.setOutAnimation(this, Android.Resource.Animation.SlideOutRight);
    
    //Using custom animations defined in XML
    flipper.setInAnimation(this, Resource.Animation.slide_in_right);
    flipper.setOutAnimation(this, Resource.Animation.slide_out_left);