Android補間動畫設置后不執行(我踩的一個大坑)


問題描述

寫了一個透明動畫(AlphaAnimation),很簡單,就是讓一個圖片從不透明到透明循環兩次。
點擊按鈕,執行動畫,動畫卻沒有執行。但是使用Debug發現,代碼確實執行了,只是沒有顯示出效果。
還有一個奇怪的情況,就是當我點擊了按鈕,且代碼執行之后,讓當前activity重寫走一遍onResume方法,動畫效果就展示出來了。
代碼如下

  • 方式一:代碼中動態設置透明動畫
    //透明動畫(AlphaAnimation)
    public void btAlphaAnimation() {
        //創建透明動畫對象
        Animation animation = new AlphaAnimation(1, 0);
        //添加屬性:動畫播放時長
        animation.setDuration(1000);
        //添加屬性:設置重復播放一次(總共播放兩次)
        animation.setRepeatCount(1);
        //設置動畫重復播放的模式
        animation.setRepeatMode(Animation.RESTART);
        //給圖片控件設置動畫
        ivPenguin.setAnimation(animation);
        //啟動
        animation.start();
}
  • xml 中配置並在activity中取調用
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromAlpha="1.0"
    android:repeatCount="1"
    android:repeatMode="reverse"
    android:toAlpha="0.0">
</alpha>

//下面是activity中執行代碼
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_my_alpha);
ivPenguin.setAnimation(animation);
animation.start();

不知道小伙們看到這里是否有發現問題?

問題就出在:setAnimation() 這個方法上,如果使用:startAnimation()方法,則不會出現上述的問題。

兩個方法的源碼如下

setAnimation

    public void setAnimation(Animation animation) {
        mCurrentAnimation = animation;
        if (animation != null) {
            // If the screen is off assume the animation start time is now instead of
            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
            // would cause the animation to start when the screen turns back on
            if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF
                    && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
            }
            animation.reset();
        }
    }

startAnimation

    public void startAnimation(Animation animation) {
        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
        setAnimation(animation);
        invalidateParentCaches();
        invalidate(true);
    }

其實通過源碼可以看到,startAnimation方法的底層也調用了setAnimation這個方法。但是startAnimation還執行了invalidate(true),而該方法的作用大家應該了解,是用於UI刷新的。動畫設置后,肯定需要UI的刷新才能展示出效果。

PS:很高興能和大家分享這樣一遍能解決BUG的文章,期待以后能和大家分享更多更有意義的文章。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM