[英]Animate button move and set new position in Android
我有一个ImageButton,我想在按下时移动,当动画结束时,我希望这个按钮在新位置停止。
这是按钮代码:
<ImageButton
android:id="@+id/move_button"
android:layout_width="120dp"
android:layout_height="35dp"
android:layout_centerInParent="true"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:scaleType="fitCenter"
android:background="@drawable/background_button"
android:src="@drawable/move_button"
android:onClick="MoveButton" />
我在这个网站上找到了一个代码:
public void MoveButton(final View view) {
TranslateAnimation anim = new TranslateAnimation(0, 0, 100, 0);
anim.setDuration(300);
anim.setAnimationListener(new TranslateAnimation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation)
{
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
params.topMargin += -100;
view.setLayoutParams(params);
}
});
view.startAnimation(anim);
}
按下按钮时,它会启动动画,但是当动画完成时,按钮返回初始位置并且应用程序崩溃。
可能是什么问题?
这是绝对的工作。
Button im= (Button) findViewById(R.id.button);
//set position TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta
final Animation animation = new TranslateAnimation(0,100,0,0);
// set Animation for 5 sec
animation.setDuration(5000);
//for button stops in the new position.
animation.setFillAfter(true);
im.startAnimation(animation);
使用anim.setFillAfter(true)
将View
放置在Animation结束的位置。
更重要的是你在Y坐标中将ImageButton
动画从100设置为0,这就是为什么你的ImageButton
到达初始位置,因为0是它的初始位置。
尝试下面在此代码我用代码anim.setFillAfter(true)
和动画 ImageButton
Y中从0到100的坐标。
public void MoveButton(final View view) {
TranslateAnimation anim = new TranslateAnimation(0,0,0,100);
anim.setDuration(300);
anim.setFillAfter(true);
anim.setAnimationListener(new TranslateAnimation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
});
view.startAnimation(anim);
}
如果这对您有帮助,请告诉我。
使用ObjectAnimator
ObjectAnimator animation = ObjectAnimator.ofFloat(YOUR_VIEW, "translationX", 100f);
animation.setDuration(2000);
animation.start();
此代码将在2秒内将View
100像素向右移动。
如果您需要更多信息,请转到“ 开发人员指南”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.