Java – Animate button movement and set a new position in Android

Animate button movement and set a new position in Android… here is a solution to the problem.

Animate button movement and set a new position in Android

I

have an ImageButton and I want to move it when I press it, and when the animation ends I want this button to stop in a new position.

Here is the button code:

<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" />

I found the code to do this on this site :

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);

}

It starts the animation when the button is

pressed, but when the animation is complete, the button returns to its initial position and the application crashes.

What could be the problem?

Solution

It’s definitely work.

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);

Related Problems and Solutions