Android只提供了4种基本动画效果,除了可以叠加效果外,我们还可以进行自定义动画。
package com.customanim.customanim; import android.app.Activity; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { private CustomAnim ca; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ca = new CustomAnim(); ca.setDuration(1000); findViewById(R.id.btnAnimMe).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { arg0.startAnimation(ca); } }); } }
一、平移动画效果:
package com.customanim.customanim; import android.view.animation.Animation; import android.view.animation.Transformation; public class CustomAnim extends Animation { @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override protected void applyTransformation( float interpolatedTime//0-1s时间 , Transformation t//变化对象 ) { t.getMatrix().setTranslate(200*interpolatedTime,//沿X轴变化
200*interpolatedTime//沿Y轴变化
); super.applyTransformation(interpolatedTime, t); } }
二、摇晃动画效果:
package com.customanim.customanim; import android.view.animation.Animation; import android.view.animation.Transformation; public class CustomAnim extends Animation { @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override protected void applyTransformation( float interpolatedTime//0-1s时间 , Transformation t//变化对象 ) { /* * Special cases: sin(+0.0) = +0.0 sin(-0.0) = -0.0 sin(+infinity) = NaN sin(-infinity) = NaN sin(NaN) = NaN 参数: d the angle whose sin has to be computed, in radians. 返回: the sine of the argument. */ t.getMatrix().setTranslate((float) (Math.sin(interpolatedTime*20//控制摇晃的时间/频率
)*50//控制摇晃的距离
), 0); super.applyTransformation(interpolatedTime, t); } }