2013-01-19 34 views
6

我試圖做一個alpha並在RelativeLayout中進行翻譯。我同時定義:在同一個佈局中啓動兩個動畫

AlphaAnimation alpha; 
alpha = new AlphaAnimation(0.0f, 1.0f); 
alpha.setDuration(1500); 
alpha.setFillAfter(true); 

TranslateAnimation translate; 
translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0,                  
       Animation.RELATIVE_TO_SELF, 0, 
       Animation.RELATIVE_TO_SELF, 1, 
       Animation.RELATIVE_TO_SELF, 0); 
translate.setDuration(1000); 

於是我開始動畫在我的RelativeLayout

RelativeLayout.startAnimation(translate); 
RelativeLayout.startAnimation(alpha); 

的問題是,在這種情況下,只有奧飛動漫開始,而不是翻譯。有人能幫我嗎?問題是如何在同一對象中同時啓動兩個不同的動畫(相對佈局在我的情況下)


我解決了這個問題。我添加它:

AnimationSet animationSet = new AnimationSet(true); 
animationSet.addAnimation(alpha); 
animationSet.addAnimation(translate); 

RelativeLayout.startAnimation(animationSet); 

回答

5

您當前的代碼將無法正常工作,因爲一旦第一個動畫開始,第二個結束,並開始自己。所以你需要等到它完成。

試試這個:

translate.setAnimationListener(new AnimationListener() { 

    public void onAnimationStart(Animation animation) { 
     // TODO Auto-generated method stub 

    } 

    public void onAnimationRepeat(Animation animation) { 
     // TODO Auto-generated method stub 

    } 

    public void onAnimationEnd(Animation animation) { 
     // TODO Auto-generated method stub 
     RelativeLayout.startAnimation(alpha); 
    } 
}); 

如果要同時執行它們,我建議你創建你的RES /動畫/文件夾中的文件animation.xml。

例子:

<?xml version="1.0" encoding="utf-8"?> 
<set 
xmlns:android="http://schemas.android.com/apk/res/android"> 
<scale 
android:fromXScale="1.0" 
android:fromYScale="1.0" 
android:toXScale=".75" 
android:toYScale=".75" 
android:duration="1500"/> 
<rotate 
android:fromDegrees="0" 
android:toDegrees="360" 
android:duration="1500" 
android:pivotX="50%" 
android:pivotY="50%" /> 
<scale 
android:fromXScale=".75" 
android:fromYScale=".75" 
android:toXScale="1" 
android:toYScale="1" 
android:duration="1500"/> 
</set> 

Java代碼:

http://developer.android.com/reference/android/view/animation/AnimationSet.html

爲:

Animation multiAnim = AnimationUtils.loadAnimation(this, R.anim.animation); 
    RelativeLayout.startAnimation(multiAnim); 
7

如果你想運行在相同的兩個時間動畫您可以使用動畫集exeample;

as = new AnimationSet(true); 
as.setFillEnabled(true); 
as.setInterpolator(new BounceInterpolator()); 

TranslateAnimation ta = new TranslateAnimation(-300, 100, 0, 0); 
ta.setDuration(2000); 
as.addAnimation(ta); 

TranslateAnimation ta2 = new TranslateAnimation(100, 0, 0, 0); 
ta2.setDuration(2000); 
ta2.setStartOffset(2000); // allowing 2000 milliseconds for ta to finish 
as.addAnimation(ta2);