2009-11-06 29 views
5

我想交換兩個按鈕的位置。 我交換代碼看起來是:兩個按鈕的動畫交換位置

private void exchangeButtons(Button btn1, Button btn2) { 
    // Create the animation set 
    AnimationSet exchangeAnimation = new AnimationSet(true); 
    TranslateAnimation translate = new TranslateAnimation(
     Animation.RELATIVE_TO_SELF, btn2.getLeft(), 
     Animation.RELATIVE_TO_SELF, btn1.getLeft(), 
     Animation.RELATIVE_TO_SELF, btn2.getRight(), 
     Animation.RELATIVE_TO_SELF, btn1.getRight()); 
    translate.setDuration(500); 
    exchangeAnimation.addAnimation(translate); 
    //int fromX = btn1.getLeft(); 
    //int fromY = btn1.getRight(); 
    //int toX = btn2.getLeft(); 
    //int toY = btn2.getRight(); 
    Log.d("ArrangeMe", 
     "view1 pos:" + btn1.getLeft() + ", 
     " +btn1.getRight() + "view2 pos:" + 
     btn2.getLeft() + ", " + btn2.getRight()); 
    AnimationSet exchangeAnimation1 = new AnimationSet(true); 
    TranslateAnimation translate1 = new TranslateAnimation( 
     Animation.RELATIVE_TO_SELF, btn1.getLeft(), 
     Animation.RELATIVE_TO_SELF, btn2.getLeft(), 
     Animation.RELATIVE_TO_SELF, btn1.getRight(), 
     Animation.RELATIVE_TO_SELF, btn2.getRight()); 
    translate1.setDuration(500); 
    exchangeAnimation1.addAnimation(translate1); 
    // EXECUTE btn1.startAnimation(exchangeAnimation); 
    btn2.startAnimation(exchangeAnimation1); 
} 

我打電話的代碼如下:

exchangeButtons(button1, button2); 

我的佈局看起來如下:當我執行的代碼是

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 

    <Button 
     android:text="One" 
     android:id="@+id/button1" 
     android:layout_height="70px" 
     android:layout_width="70px" 
     android:layout_weight="1"> 
    </Button> 
    <Button 
     android:text="Two" 
     android:id="@+id/button2" 
     android:layout_height="70px" 
     android:layout_width="70px" 
     android:layout_weight="1"> 
    </Button> 
</LinearLayout> 

會發生什麼:

而不是按鈕交換他們的立場,他們只是消失了一段時間[可能是500毫秒],並重新出現。

如何解決此問題?它會在設備中正常工作嗎?

+0

你解決這個問題呢? – 2012-02-05 16:12:27

回答

1

Android的TranslateAnimation不會重定位您的組件,它只是爲您想要做的轉換創建動畫 - 之後,由您決定更改組件的佈局參數(看看這個post)。

P.S.您可以直接使用翻譯動畫,而無需使用全新的動畫集。另一件好事將是在佈局膨脹時創建動畫並覆蓋onSizeChanged(int, int, int, int)以使用新維度重新創建動畫。

您使用的是什麼佈局?

3

您不會在onCreate中獲得getRight值,因爲UI尚未繪製在屏幕上,因此沒有UI元素進行測量。試試這個

ViewTreeObserver vto = btn1.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     btn1.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
     int left = btn1.getLeft(); 
    } 
}); 

把代碼在onCreate方法