此代码通过y-position
和ObjectAnimator
点击按钮点击两个视图(mView1和mView2)的AnimationSet
。在翻译动画中,两个视图的alpha
值将会减少并再次增长。这只是一个可以玩一下的设置。 alpha动画以XML格式定义,翻译动画以代码完成。
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:ordering="sequentially">
<objectAnimator
android:propertyName="alpha"
android:duration="500"
android:valueTo="0.5"
android:valueType="floatType"/>
<objectAnimator
android:propertyName="alpha"
android:duration="500"
android:valueTo="1.0"
android:valueType="floatType"/>
</set>
@Override
public void onClick(View v) {
if (mView1 != null && mView2 != null) {
int top = mView2.getTop();
ObjectAnimator translateView1 = null;
ObjectAnimator translateView2 = null;
if (mView1.getTranslationY() == 0) {
translateView1 = ObjectAnimator.ofFloat(mView1, "translationY", top);
translateView2 = ObjectAnimator.ofFloat(mView2, "translationY", top*(-1));
} else {
translateView1 = ObjectAnimator.ofFloat(mView2, "translationY", 0);
translateView2 = ObjectAnimator.ofFloat(mView1, "translationY", 0);
}
translateView1.setDuration(1000L);
translateView2.setDuration(1000L);
AnimatorSet alpha1 = (AnimatorSet)AnimatorInflater.loadAnimator(mCtx, R.anim.switcher);
alpha1.setTarget(mView1);
AnimatorSet alpha2 = (AnimatorSet)AnimatorInflater.loadAnimator(mCtx, R.anim.switcher);
alpha2.setTarget(mView2);
AnimatorSet set = new AnimatorSet();
set.playTogether(translateView1, translateView2, alpha1, alpha2);
set.start();
}
}
现在,因为这是按预期工作的,我想知道如何缩短代码?
是否真的有必要为每个AnimatorSet
使用View
的单独实例,它使用来自XML的动画?我可以将xml充气一次并在不同的AnimatorSets / ObjectAnimators上使用吗?因为我没有找到一个以Animator为论据的制定者。
我可以为一个AnimationSet / ObjectAnimator定义多个目标吗?或者是为视图定义不同ObjectAnimator并在AnimationSet中使用它们的唯一方法吗?
答案 0 :(得分:1)
您需要将动画代码放在动画类中......就像这样:
public class FadingView extends View {
private ObjectAnimator fade, moveX, moveY;
private AnimatorSet moveSet;
public FadingView(Context context) {
super(context);
}
private void fade(int duration, float...values) {
if(fade==null) {
fade = ObjectAnimator.ofFloat(this, "alpha", values);
} else {
fade.setFloatValues(values);
}
fade.setDuration(duration);
fade.start();
}
private void move(int duration, int x, int y) {
if(moveX==null) {
moveX = ObjectAnimator.ofFloat(this, "translation_x", x);
} else {
moveX.setFloatValues(x);
}
if(moveY==null) {
moveY = ObjectAnimator.ofFloat(this, "translation_y", y);
} else {
moveY.setFloatValues(y);
}
if(moveSet == null) {
moveSet = new AnimatorSet();
moveSet.playTogether(moveX, moveY);
}
moveSet.setDuration(duration);
moveSet.start();
}
public void moveToUpperLeft(int duration) {
move(duration, 0,0);
}
public void show(int duration) {
fade(duration,1);
}
public void hide(int duration) {
fade(duration,0);
}
}
只是一个基本的例子,但现在你可以打电话:
FadingView view = new FadingView(context);
view.hide(500);
view.moveToUpperLeft(500);
当然,你可以更加自定义和概括......