Search code examples
androidimageviewd-pad

Wondering how to make an ImageView slide at a constant rate?


I'm basically programming a D-Pad for a video game, and I'm trying to figure out how to make an ImageView move at a constant X or Y, then keep that position after the button is released.

Any help or questions about what I'm doing specifically would be very much appreciated.


Solution

  • You can use ObjectAnimator.ofFloat(Object target, String property, float values...)

    Set it a LinearInterpomator so that the animation is constant in its progress.

    Example :

    ObjectAnimator animator = ObjectAnimator.ofFloat(myImage, "X", 0f, 150f);

    Set interpolator : animator.setInterpolator(new LinearInterpolator());

    A duration in milliseconds : animator.setDuration(5000); //5 seconds

    Then start it.

    It will move your image from 0 on the X axis to 150. The String property refers to the object property on which you want to apply the new coordinates value.

    I hope it helped.

    Note : you may change the from and to values so that the from value correspond to the actual position of the image and so that the destination coordinate is actually the new position would want.

    There are other solutions such as KitKat TransitionManaqger but should you want to target devices before KitKat you may use ObjectAnimator.