Search code examples
androidanimationandroid-animationvisibility

Animate visibility of a view from gone to visible with animation


I have a view that is invisible by default(Just for the first time).

Now I need to switch the visibility to VISIBLE with this animation:

if (myView.getVisibility() == View.INVISIBLE) {
    myView.setVisibility(View.VISIBLE);
    myView.animate().translationY(0);
 }

(Like the SnackBar default animation)

But this isn't working. It will turn visible with default animation

Is there any simple way that I could achieve this?

Note

I'm animating my view to dismiss, like this:

myView.animate().translationY(myView.getHeight());

Solution

  • You can do this using XML animation.

    Create a slide-up animation XML using set and alpha and put this XML into your resource anim folder.

    slide_up.xml

    <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android" >
    
        <translate
            android:duration="500"
            android:fromYDelta="100%"
            android:toYDelta="0" />
    </set>
    

    USE:

    Use AnimationUtils.loadAnimation() to load animation from XML and set and start animation using .startAnimation() method.

    Here is an example:

    ImageView imageView = (ImageView) findViewById(R.id.imageView);
    
    // slide-up animation
    Animation slideUp = AnimationUtils.loadAnimation(this, R.anim.slide_up);
    
    if (imageView.getVisibility() == View.INVISIBLE) {
        imageView.setVisibility(View.VISIBLE);
        imageView.startAnimation(slideUp);
    }
    

    Hope this will help~