Skip to content
Advertisement

How to do translate animation of button in Android Studio?

I am trying to move a button from one site to another. I manage to move it but when it moves, I have to click on the place where it was before instead of hitting the button. Why does this happen?

This is how it looks. You can see how at the end when I click on another side, the button’s shadow is activated

My code:

Animation xaml

move.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    >

    <translate
        android:fromYDelta="0%p"
        android:fromXDelta="0%p"
        android:toXDelta="-300"
        android:toYDelta="-300"
        android:duration="500"
        ></translate>

</set>

In the code:

    Animation animation = AnimationUtils.loadAnimation(this,R.anim.move);
    btnNext.startAnimation(animation);

Advertisement

Answer

This happens because the animation is performed by changing the translationX and translationY view properties, not the actual position which the ui framework authors, in their infinitesimal wisdom, have placed in an external class, inheriting LayoutParams. Consequently the click events are dispatched to the “raw” position of the view which does not account for the view transformations (reference). Animations in android are still pretty tedious and untamed but at least there are many approaches to take. For this case a ValueAnimator for the LayoutParams fields seems like a solution. If the layout allows margins then it can look like this:

final ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) btnNext.getLayoutParams();
int initialX = displayWidth - btnNextWidth, finalX = displayWidth / 2;

ValueAnimator.ofInt(initialX, finalX)
    .setDuration(500)
    .addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
         @Override
         public void onAnimationUpdate(ValueAnimator valueAnimator) {
             Integer ax = (Integer) valueAnimator.getAnimatedValue();
             Log.i("anim", "x: " + ax);
             lp.leftMargin = ax;
             btnNext.requestLayout();
         }
    });
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement