上节讲了属性动画的基本原理,有了这些原理,我们就不难理解API提供的处理类和相关接口了。
Android属性动画的主要类是ValueAnimator, 下面就来实现一个简单的动画,我们将一行字从屏幕的左端按减速规则移动到右端。
public class MainActivity extends Activity {
ValueAnimator animator;
TextView helloworldText;
Button startBtn;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
public void initViews() {
helloworldText = (TextView) findViewById(R.id.helloworlTxt);
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//启动动画
startAnimator();
}
});
}
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void startAnimator() {
// 获取屏幕宽度
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
// 获取view的宽度
int hellowordTextSize = helloworldText.getWidth();
// 设定value变化区间,系统会使用IntEvalator计算AnimatedValue
animator = ValueAnimator.ofInt(0, screenWidth - hellowordTextSize);
// 持续时间3000ms
animator.setDuration(3000);
// 使用减速插值算法,DecelerateInterpolator的参数表示值变化的快慢度
animator.setInterpolator(new DecelerateInterpolator(1f));
// 当value更新时触发的监听器,触发间隔与frame delay有关,默认为10ms,当然可以通过
// animator.setFrameDelay(frameDelay)
animator.addUpdateListener(new MyUpdateListener());
// 启动value改变过程
animator.start();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
private class MyUpdateListener implements ValueAnimator.AnimatorUpdateListener {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
// TODO Auto-generated method stub
// 取得经插值计算后的value值
Integer value = (Integer) animator.getAnimatedValue();
int currentX = value;
// 改变当前text view的x坐标
helloworldText.setX(currentX);
// 当然也可以通过取fraction的方法,重新计算x的坐标
// float fraction = animator.getAnimatedFraction();
// int currentX = fraction * ( screentWidth - hellowordTextSize - 0
// )
// helloworldText.setX(currentX);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}