2009-11-06 7 views
5

2つのボタンの位置を入れ替えようとしています。 マイスワッピングコードが見えることである。2つのボタンのアニメーションスワップ位置

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> 

次のとおりです。

ボタンの位置を入れ替えるのではなく、いつか消えます[ 500msであるかもしれない]、それらがもともとあったように再び現れる。

この問題を解決するにはどうすればよいですか?デバイスで正常に動作しますか?

+0

にコードを入れてみては? –

答えて

1

AndroidのTranslateAnimationは、コンポーネントの配置を変更しません。その場合は、コンポーネントのレイアウトパラメータを変更する必要があります(この後はpostをご覧ください)。

P.S.まったく新しいアニメーションセットを使用せずに、翻訳アニメーションを直接使用することができます。別の良いことは、レイアウトが膨張したときにアニメーションを作成し、onSizeChanged(int, int, int, int)をオーバーライドして、新しい寸法を使用してアニメーションを再作成することです。

使用しているレイアウトは何ですか?

3

onCreateでgetRight値を取得することはありません。これは、UI要素がまだ計測されていないため、画面に描画されていないためです。この

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

は、あなたがこの問題を解決しましたのonCreateメソッド

関連する問題