我正在尝试交换两个按钮的位置。 我的交换代码看起来是:
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 毫秒],然后像原来一样重新出现。
如何解决这个问题?它会在设备中正常工作吗?
最佳答案
您不会在 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方法中
关于android - 两个按钮的动画交换位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1686846/