0
点赞
收藏
分享

微信扫一扫

Pro Android学习笔记(一一二):2D动画(7):Property Animation(上)


作者@恺风Wei。

Animation API在Android3.0后有很大的变化,新的方式成为property animation(属性动画)。我们在之前的Pro Android学习笔记(四二):Fragment(7):切换效果中已经接触过。前面学习的2D动画属于旧的animation API,由android.view.animation包实现,而新的animaition API是在android.animation包中。

ValueAnimation

属性动画描述的是一组变化,这个变化可以针对某个数值,也可以针对某个对象。下面先看看最简单的针对数值的变化。

private void basicPropertyTest(){ 
     showInfo("Basic Property Test"); 
    ValueAnimator anim = ValueAnimator.ofInt(10,200);   //设置从10到200变化的整数,缺省每10ms变化一次,如果是模拟器,由于性能缘故,间隔大于10ms。      anim.setDuration(5000); //渐变的时间为5秒

     anim.addUpdateListener(new AnimatorUpdateListener() {  //数值变化的回调函数         
         @Override 
         public void onAnimationUpdate(ValueAnimator animation) {  
             int value = (Integer) animation.getAnimatedValue(); 
             showInfo("update: " + value); 
         } 
     });  
      
     anim.addListener(new AnimatorListener() {    //用于检测变化的状态,例如开始,结束
         @Override 
         public void onAnimationStart(Animator animation) {  
             showInfo("onAnimationStart"); 
         }          
         @Override 
        public void onAnimationRepeat(Animator animation) {  
             showInfo("onAnimationRepeat"); 
         }          
         @Override 
        public void onAnimationEnd(Animator animation) {  
             showInfo("onAnimationEnd"); 
         }          
         @Override 
        public void onAnimationCancel(Animator animation) {  
             showInfo("onAnimationCancel"); 
         } 
     });  
  
     anim.start(); 
 } 

private void showInfo(String info){ 
     Log.v("WEI",info); 
     tv.setText(info + "\n" + tv.getText()); 
 }

对应到View的ObjectAnimation

通过ValueAnimation我们了解了属性动画的回调函数。下面小例子将用于View。

代码片段如下:

.... 
     TextView tv = (TextView)findViewById(R.id.text_property); 
     .... 

 public void toggleAnimation(View v){ 
     Button button = (Button)v; 
     if(tv.getAlpha() != 0){  //检查当前的alpha的数值,如果大于0(可视)就将之变为不可视(=0)
        ObjectAnimator fadeout = ObjectAnimator.ofFloat(tv, "alpha", 0.0f); //将alpha从当前值变为0(看不见),ofFloat()表明这是对tv对象(参数1)的alpha属性(参数2)进行的浮点类型数值的变化,从当前值变化至目标值(参数3)。哪些可以作为属性,需要具备setXXX()方法,则具备XXX属性,本例Textview对象具有public方法view.setAlpha(float f)方法,故具有属性alpha。初始值从view.getAlpha()中获取。如果带有4个参数,例如ofFloat(tv,"alpha",1.0f,0.0f),则第三个参数标识from的数值,第4个参数标识to的数值,即从alpha属性从1.0变为0.0。        fadeout.setDuration(5000); 
         fadeout.start(); 
         button.setText("Fade In"); 
    }else{ 
         ObjectAnimator fadeIn = ObjectAnimator.ofFloat(tv, "alpha", 1.0f);//将alpha从当前值变为1        fadeIn.setDuration(5000); 
         fadeIn.start(); 
         button.setText("Fade Out"); 
     } 
 }

小例子代码在:Pro Android学习:2D动画小例子


举报

相关推荐

【Unity3D】2D动画

0 条评论