两个按钮的动画交换位置

Jag*_*gat 5 animation android swap button

我试图交换两个按钮的位置.我的交换代码看起来是:

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);
}
Run Code Online (Sandbox Code Playgroud)

我将代码调用如下:

exchangeButtons(button1, button2);
Run Code Online (Sandbox Code Playgroud)

我的布局如下:

<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>
Run Code Online (Sandbox Code Playgroud)

执行代码时会发生什么:

它们不是交换位置的按钮,而是消失了一段时间[可能是500毫秒]并重新出现.

如何解决这个问题?它能在设备上正常工作吗?

Dim*_*rov 1

Android TranslateAnimation不会重新定位您的组件,它只是为您想要执行的转换设置动画 - 之后,您就可以更改组件的布局参数(看看这篇文章

PS 您可以直接使用平移动画,而无需使用全新的动画集。另一个好处是在布局膨胀时创建动画并覆盖onSizeChanged(int, int, int, int)以使用新尺寸重新创建它们。

您使用的布局是什么?