Android 常见动画为补间动画(透明,缩放,平移,旋转)与帧动画。下面说说补间动画的实现。
1.在配置文件中建立动画
在res目录下建立anim文件夹,在res/anim目录下建立动画配置文件如下:
透明动画alpha.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" > <!-- 各动画可以混合 --> <!-- alhpa 代表透明 fromAlpha 从哪个透明多0.0(透明)~1.0(不透明) toAlpha 到哪个透明度 duration 变化时间 --> <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" > </alpha> </set>
旋转动画rotate.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <!-- rotate 旋转 fromDegrees 开始角度 toDegrees 结束角度 (正数表示顺时针,负数表示逆时针) pivotX 旋转参考点 pivotY --> <rotate android:fromDegrees="0.0" android:toDegrees="180.0" android:pivotX="50%" android:pivotY="50%" android:duration="5000" > </rotate> </set>
缩放动画scale.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <!-- scale 缩放 下面相当于放大5倍 --> <scale android:fromXScale="1.0" android:fromYScale="1.0" android:toXScale="5.0" android:toYScale="5.0" android:pivotX="50%" android:pivotY="50%" android:duration="5000" > </scale> </set>
平移动画translate.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <!-- translate 平移动画 --> <translate android:fromXDelta="0.0" android:toXDelta="200.0" android:fromYDelta="0.0" android:toYDelta="300.0" android:duration="5000" > </translate> </set>
各动画可以融合在一起。
然后对相应的ImageView进行动画设置
public class MainActivity extends Activity { ImageView image; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image=(ImageView) findViewById(R.id.anim); //透明 // Animation animation= AnimationUtils.loadAnimation(this,R.anim.alpha); // image.startAnimation(animation); //平移 Animation animation= AnimationUtils.loadAnimation(this,R.anim.translate); animation.setFillAfter(true); //设置动画最后保持的状态 image.startAnimation(animation); //旋转 // Animation animation= AnimationUtils.loadAnimation(this,R.anim.rotate); // image.startAnimation(animation); //缩放 // Animation animation= AnimationUtils.loadAnimation(this,R.anim.scale); // image.startAnimation(animation); } }
2.通过代码动态创建动画,不需要配置文件
//动态创建透明动画(不需要配置文件) AlphaAnimation animation2=new AlphaAnimation(1.0f,0.0f); animation2.setDuration(5000); image.startAnimation(animation2);