1

我想在Android項目中製作簡單的動畫。我在我的活動得到了一個形象:在Android中旋轉動畫序列

<ImageView 
     android:id="@+id/pointer_png" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:scaleType="fitCenter" 
     android:adjustViewBounds="true" 
     android:layout_gravity="center" 
     android:src="@drawable/pointer_400" /> 

這裏是在活動課我的onClick方法:

public void onStartButtonClick(View view){ 
    AnimationSet animationSet = new AnimationSet(true); 
    animationSet.setInterpolator(new LinearInterpolator()); 
    animationSet.setFillAfter(true); 

    RotateAnimation anim = new RotateAnimation(0.0f, -45.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); 
    anim.setDuration(4000); 
    animationSet.addAnimation(anim); 

    RotateAnimation anim2 = new RotateAnimation(0.0f, 90.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); 
    anim2.setDuration(4000); 
    animationSet.addAnimation(anim2); 

    RotateAnimation anim3 = new RotateAnimation(0.0f, -135.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); 
    anim3.setDuration(4000); 
    animationSet.addAnimation(anim3); 

    RotateAnimation anim4 = new RotateAnimation(0.0f, 180.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); 
    anim4.setDuration(4000); 
    animationSet.addAnimation(anim4); 

    final ImageView pointer = (ImageView) findViewById(R.id.pointer_png); 
    pointer.startAnimation(animationSet); 
} 

不幸的是,效果出人意料。我想按以下順序旋轉圖像:

  1. 在4秒內旋轉180度。
  2. 在接下來的4秒內旋轉-135度。
  3. 在接下來的4秒內旋轉90度。
  4. 最近4秒內旋轉-45度。

但是,使用此代碼動畫絕對短於16秒,它僅由一個部分組成 - 從0點開始90度並結束。可能AnimationSet會檢查所有動畫並計算序列中的最後位置。我試圖設置AnimationSet(false)併爲每個RotateAnimation添加單獨的LinearInterpolator,但它不起作用。

我應該怎樣做才能讓我的動畫更長,並且所有的旋轉都是分開的(4步,每步4秒)?

+0

嘗試使用'setStartOffset()'將起始偏移添加到其他動畫中。 – TR4Android

+0

我已經嘗試了偏移量:0,4000,8000和12000,但最終效果非常好,並且出乎意料。我擔心我需要爲每個動畫設置AnimationListener並覆蓋onAnimationEnd方法,然後開始下一個動畫。這個序列可以,但是更復雜的動畫是什麼? – maniek099

回答

0

從我的經驗AnimationSet並不總是按預期工作,並且可以在一個痛**。我會嘗試使用ViewPropertyAnimator

這是一個關於如何使用它的例子。您可以設置startDelay所佔用的是這樣的:

pointer.animate() 
    .rotation(...) // <- enter rotation values here 
    .setStartDelay(4000) 
    .setInterpolator(new LinearInterpolator()) 
    .setDuration(4000); 

或設置AnimationListener並開始下一個動畫onAnimationEnd()當一個之前完成。

自發的,如果我不得不這樣做我會寫我自己的方法,這樣的事情(未測試):

private void rotate(View v, float rotation, int startDelay) { 
    v.animate() 
    .rotation(rotation) // or rotationBy(rotation) whichever suits you better 
    .setStartDelay(startDelay) 
    .setInterpolator(new LinearInterpolator()) 
    .setDuration(4000); 
} 

,然後調用四次這樣的:

rotate(pointer, -45, 0); 
rotate(pointer, 90, 4000); 
rotate(pointer, -135, 8000); 
rotate(pointer, 180, 12000);