ObjectAnimator没有暂停

时间:2014-09-11 12:53:43

标签: android android-activity android-animation

我正在尝试向addPauseListener对象添加ObjectAnimator,但这不会暂停对象。这是我的代码:

public class MyActivity extends Activity {

TextView txt;
ObjectAnimator anim;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    txt = (TextView) findViewById(R.id.scroll_message);

    ObjectAnimator anim = ObjectAnimator.ofFloat(txt,"translationY", -200,500);
    anim.setDuration(30000);
    anim.setRepeatCount(ObjectAnimator.INFINITE);
    anim.setRepeatMode(ObjectAnimator.REVERSE);
    anim.start();
    //anim.addPauseListener(pauseListener);

}

    /*Animator.AnimatorPauseListener pauseListener = new Animator.AnimatorPauseListener() {
        public void onAnimationPause(Animator animation) {
               animation.pause() ;
        }
        public void onAnimationResume(Animator animation) {
                animation.start();
         }
    };*/

    public boolean onTouchEvent(MotionEvent event) {
        int eventAction = event.getAction();

        if (MotionEvent.ACTION_DOWN==eventAction){
            anim.pause();
        }
        if (MotionEvent.ACTION_UP==eventAction){
            anim.resume();
        }
    return true;
    };
 }

使用此方法我收到错误:

09-11 10:02:39.431  17385-17385/com.example.rs.myapplication E/MessageQueue-JNI﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void android.animation.ValueAnimator.pause()' on a null object reference

如何获得所需的操作,以便在触摸设备时动画暂停,当未触动的动画再次恢复时?

2 个答案:

答案 0 :(得分:1)

你有2个动画对象。一个是本地的,一个是全球的。您永远不会设置全局的,只在oncreate方法中定义本地的。因此空对象错误。

更改此行:

ObjectAnimator anim = ObjectAnimator.ofFloat(txt,"translationY", -200,500);

就这样:

anim = ObjectAnimator.ofFloat(txt,"translationY", -200,500);

在oncreate方法中启动动画通常也很糟糕。我个人从来没有必要这样做,但我读过的共识是在onWindowFocusChanged方法中做到的。

答案 1 :(得分:0)

    anim.setRepeatCount(ObjectAnimator.INFINITE); //so that it's does not pause object.

您可以将计数器设置为10,20,30等动画,或者根据需要重复该对象

    anim.setRepeatCount(10); // 10 time repeat object after complete that will stop / pause