每次想到循環播放、重復執行時,腦海中總是冒出在while(true)的實現方式。
Thread thread = new Thread(new Runnable(){ public void run(){ while(true){ // do animation operation } } }).start();
但這種方式總給人一種不可靠的感覺。
為此,在這多記錄幾種實現方式,方便以后參考。
第一種:使用屬性動畫實現(ObjectAnimator)
Path path = new Path(); path.addOval(100, -500, 500, -100, Path.Direction.CW); ObjectAnimator ivGreenObjectAnimator = ObjectAnimator.ofFloat(ivRed, View.TRANSLATION_X, View.TRANSLATION_Y, path); ivGreenObjectAnimator.setDuration(5000).setRepeatCount(ValueAnimator.INFINITE); ivGreenObjectAnimator.setRepeatMode(ValueAnimator.RESTART); ivGreenObjectAnimator.start();
效果:綠色小球沿着橢圓循環運動。
第二種:使用屬性動畫實現(ViewPropertyAnimator)
private void startAnimateByViewAnimationProperty() { ViewPropertyAnimator ivGreenAnimate = ivGreen.animate();int[] positions = new int[]{600, 100, 100, 400}; ivGreenAnimate.translationX(400).setDuration(500).setListener(new ComplexAnimatorListener(ivGreen, positions)); } static class ComplexAnimatorListener implements Animator.AnimatorListener { View view; int[] positions; int times = 0; public ComplexAnimatorListener(View view, int[] positions) { this.view = view; this.positions = positions; } @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { Log.v("qian", "repeat running!"); times++; if (times % 4 == 1) { view.animate().translationY(positions[0]).setDuration(500).setListener(this); } else if (times % 4 == 2) { view.animate().translationX(positions[1]).setDuration(500).setListener(this); } else if (times % 4 == 3) { view.animate().translationY(positions[2]).setDuration(500).setListener(this); } else view.animate().translationX(positions[3]).setDuration(500).setListener(this); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }
效果:綠色小球沿着矩形循環運動。
第三種:使用一般動畫實現(TranslateAnimation)
TranslateAnimation translateAnimation = new TranslateAnimation(-400, -100, -400, -100); translateAnimation.setRepeatCount(Animation.INFINITE); translateAnimation.setRepeatMode(Animation.REVERSE); ivGreen.startAnimation(translateAnimation);
效果:小球沿着矩形循環運動。
第四種:使用handler及其callback遞歸調用實現
Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if(msg.what==1){ startAnimation(); } return false; } }); private void startAnimation(){ //do animation operation Message message = new Message(); message.what = 1; handler.sendMessage(message); }
一次執行完又執行
第五種:使用handler及其runnable遞歸調用實現
Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { ViewPropertyAnimator animate = binding.ivBlue.animate(); animate.translationXBy(-200).translationYBy(-200).scaleX(2.0f).scaleY(2.0f). setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(500).start(); printProperty(binding.ivBlue); handler.postDelayed(this, 500); } };
private void startAnimation(){
handler.postDelayed(this, 500);
}
遞歸調用postDelayed方法。