Search code examples
androidandroid-animationtranslate-animation

TranslateAnimation from middle to Top Left without cutting off view


I have a parent container called mContainer and a child view called mChildImageView. The ImageView is positioned in the middle of the container and I am trying to translate the ImageView to the top left without cutting off the ImageView.

What I would like is to translate the top most point of the ImageView to the top left part of mContainer, this way it would make the ImageView cut off.

This is the following code I am using, as you can see I am using Absolute coordinates, I would like to make it more dynamic how can I accomplish this?

TranslateAnimation a = new TranslateAnimation(
            Animation.ABSOLUTE,             // Specifies X-Type interpretation, ABSOLUTE, RELATIVE_TO_SELF, RELATIVE_TO_PARENT
            0.0f,                           // Change in x coordinate at start of animation, can be absolute or percentage if RELATIVE
            Animation.ABSOLUTE,
            -30,                            // Change in x coordinate at end of animation, can be absolute or percentage if RELATIVE
            Animation.ABSOLUTE,             // Specifies Y-Type interpretation, ABSOLUTE, RELATIVE_TO_SELF, RELATIVE_TO_PARENT
            0.0f,                           // Change in y coordinate at start of animation, can be absolute or percentage if RELATIVE
            Animation.ABSOLUTE,
            30                              // Change in y coordinate at end of animation, can be absolute or percentage if RELATIVE
    );

mChildImageView.setAnimation(a);
mChildImageView.animate();

Solution

  • If you want to change TranslationX or/and TranslationY parameters of a view with relation to its parent, I highly recommend you to use Animators instead of Animations as they have some drawbacks (for example: Android - Animation Issue).

    Possible variant:

    mChildImageView.animate().translationX(newTranslationX).translationY(newTranslationY).setDuration(duration).start();