首页 > 解决方案 > 如何通过xml将一组动画放在2个按钮上?

问题描述

我正在为我的按钮设置动画,当我单击一个按钮时,该按钮应该沿 y 轴移动并淡出,而另一个按钮将在 y 轴上淡入。我通过在我的 java 类中编写代码实现了这一点,它工作得很好,但我想将所有代码转移到我的 XML 并从那里调用。这些动画。我怎样才能以这种方式制作一组动画,即翻译、淡出和另一个翻译和淡入?

 public static void crossfade(Button buttonToFadeOut, Button buttonToFadeIn) {

    buttonToFadeIn.setAlpha(0f);
    buttonToFadeIn.setVisibility(View.VISIBLE);

    buttonToFadeIn.animate()
            .alpha(1f)
            .translationY(100)  //220
            .setDuration(700)
            .setStartDelay(60)
            .setListener(null);

    buttonToFadeOut.animate()
            .alpha(0f)
            .setDuration(700)
            .translationY(-100)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    buttonToFadeOut.setVisibility(View.GONE);
                }
            });
}

标签: androidandroid-studiouser-interfaceanimationbutton

解决方案


这是在 XML 中进行淡出的方法:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">
    <alpha
        android:duration="1700"
        android:fromAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="0.0" />
</set>

res您必须在调用中创建一个新的 Android 资源目录,anim并在该文件夹中创建上述文件anim

现在,要在 Java 中调用该动画,您必须执行以下操作:

Animation anim = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fadeout);

现在,要在您的按钮上应用此动画,您将执行以下操作:

button.startAnimation(anim);

在此处的链接中有一个非常有用的视频,它解释了如何为各种动画制作 XML 文件。我希望这个答案是有用的。


推荐阅读