Using fade in animation for a view

2019-01-13 07:48发布

问题:

I want to have a View that initially is invisible and when I press a button, it becomes visible with a fade in animation. I'm using the AlphaAnimation for the fading effect. The problem is that if I make the view invisible the animation can't be seen.

Thanks a lot,

Gratzi

回答1:

Provide an AnimationListener to the Animation and make the View visible as soon as the Animation starts.

http://developer.android.com/reference/android/view/animation/Animation.AnimationListener.html



回答2:

Suppose you have an ImageView named imageView and an animation file your_fade_in_anim.xml inside your res\anim\ folder:

ImageView imageView = (ImageView) findViewById(R.id.imageView);
Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.your_fade_in_anim);
// Now Set your animation
imageView.startAnimation(fadeInAnimation);

Your XML

<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha 
        android:fromAlpha="0.0"
        android:toAlpha="1.0" 
        android:interpolator="@android:anim/accelerate_interpolator" 
        android:duration="[duration (in milliseconds)]"
        android:repeatCount="infinite" />
</set>

Replace the brackets with your actual duration.



回答3:

Instead of the infinite repeat count and hiding/viewing your View, I suggest to just not repeat the animation and initially start with the alpha channel set to maximum. Then you can use:

<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha 
        android:fromAlpha="0.0"
        android:toAlpha="1.0" 
        android:interpolator="@android:anim/accelerate_interpolator" 
        android:duration="[duration (in milliseconds)]"
        android:repeatCount="0" />
</set>

And you're done. No need for a Listener, hiding or showing. Just as simple.