zoukankan      html  css  js  c++  java
  • 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的文章,期待以后能和大家分享更多更有意义的文章。

  • 相关阅读:
    Python PEP8 编码规范中文版
    MySQL分区表
    mybatis缓存,包含一级缓存与二级缓存,包括ehcache二级缓存
    斐讯K2刷不死breed与第三方固件教程
    Mysql 多表连接查询 inner join 和 outer join 的使用
    mysql多表关联删除示例
    sublime Text 几款插件
    多进程vs多线程
    git 命令常用总结
    LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
  • 原文地址:https://www.cnblogs.com/io1024/p/11580436.html
Copyright © 2011-2022 走看看