我想在我的图像上做多个动画(出现 -> 旋转 -> 消失)。我有这段代码:
淡入淡出.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:shareInterpolator="false" >
<alpha
android:duration="1"
android:fromAlpha="0"
android:toAlpha="100" />
</set>
淡出.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:shareInterpolator="false" >
<alpha
android:duration="1"
android:fromAlpha="100"
android:toAlpha="0" />
</set>
图像旋转.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:shareInterpolator="false" >
<rotate
android:duration="2500"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="120" />
</set>
同样在我的 java 代码中:
animRotate= AnimationUtils.loadAnimation(context, R.anim.image_rotate);
animRotate.setDuration((long) duration);
fade_in = AnimationUtils.loadAnimation(context, R.anim.fade_in);
fade_out = AnimationUtils.loadAnimation(context, R.anim.fade_out);
AnimationSet s = new AnimationSet(false);
s.addAnimation(fade_in);
s.addAnimation(animRotate);
s.addAnimation(fade_out);
image.startAnimation(s);
但不幸的是它不能正常工作......
最佳答案
您的动画 xml 文件中有多个错误:
- 持续时间属性以毫秒为单位,因此 1 毫秒对于明显的淡入/淡出动画来说太短了
- alpha 属性是一个介于 0 和 1 之间的 float ,100 太多了。
- 如果只有一个动画,则不需要在 xml 文件中设置:只需添加 alpha 或 rotate 标签作为根
因此,您现在应该拥有这些文件:
淡入淡出.xml
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromAlpha="0"
android:toAlpha="1" />
淡出.xml
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromAlpha="1"
android:toAlpha="0" />
图像旋转.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="2500"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="120" />
然后,在您的代码中,您需要在每个动画之间添加一个偏移量。否则,将同时触发所有动画。此外,必须在根动画对象(此处为您的 AnimationSet
)上设置 fillAfter 标志
Animation animRotate= AnimationUtils.loadAnimation(context, R.anim.image_rotate);
Animation fade_in = AnimationUtils.loadAnimation(context, R.anim.fade_in);
Animation fade_out = AnimationUtils.loadAnimation(context, R.anim.fade_out);
AnimationSet s = new AnimationSet(false);
s.addAnimation(fade_in);
animRotate.setDuration((long) duration);
animRotate.setStartOffset(fade_in.getDuration());
s.addAnimation(animRotate);
fade_out.setStartOffset(fade_in.getDuration() + animRotate.getDuration());
s.addAnimation(fade_out);
s.setFillAfter(true);
image.startAnimation(s);
关于java - 动画出现、旋转和消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954515/