简体   繁体   English

如何在 Android Studio 中翻译按钮动画?

[英]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动画xaml

move.xml:移动.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);

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 .发生这种情况是因为动画是通过更改translationX和 translationY 视图属性来执行的,而不是 ui 框架作者以其无穷小的智慧放置在继承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. android 中的动画仍然相当乏味和野蛮,但至少有很多方法可以采用。 For this case a ValueAnimator for the LayoutParams fields seems like a solution.对于这种情况,LayoutParams 字段的 ValueAnimator 似乎是一个解决方案。 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();
         }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM