Android:动画通过代码工作,而不是通过 xml

Android: animation works by code but not by xml

我有一个非常简单的动画:图像视图必须一直上升然后下降。最初我尝试使用 xml:

<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:shareInterpolator="false"
 android:fillAfter="true">
<set
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="-1"
    android:repeatMode="reverse">
    <translate
        android:fromYDelta="0"
        android:toYDelta="10"
        android:duration="300">
    </translate>
</set>

Animation mAnimation= AnimationUtils.loadAnimation(this, R.anim.myanimation);
immagineNemico.startAnimation(mAnimation);

但是没有 work:my imageview 没有上升,只有下降。所以我阅读了一个问题的答案并通过代码制作了动画:

    immagineNemico.setVisibility(View.VISIBLE);
    TranslateAnimation mAnimation = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.02f);
    mAnimation.setDuration(300);
    mAnimation.setRepeatCount(-1);
    mAnimation.setRepeatMode(Animation.REVERSE);
    mAnimation.setInterpolator(new LinearInterpolator());
    immagineNemico.setAnimation(mAnimation);

它奏效了。但为什么 xml 动画不起作用?他们几乎是一样的!哪里出错了?

我遇到过同样的问题:动画在通过代码设置时有效,但在 XML 中无效。简短的回答是,在 Android 动画中存在 bugs/intentionally 令人困惑的设计,其中某些 XML 元素被忽略。

这个对相关问题的回答首先告诉我,以编程方式完成与通过 XML 相比,有些事情会起作用:

我知道这不是最令人满意的答案,但简而言之 - 即使 XML 是完美的,在某些情况下它也不起作用。