2014-09-11 128 views
0

我想一個addPauseListener添加到我的ObjectAnimator對象,但這並不暫停object.This是我的代碼: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 

如何獲得所需的操作,以便在觸摸設備時動畫會暫停,並且當未觸動的動畫再次恢復時?

回答

1

你有2個動畫對象重複對象。一個是本地和一個全球。你從來沒有設置全局的,你只能在oncreate方法中定義本地的。因此空對象錯誤。

改變這一行:

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

爲了眼前這個:

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

還有一點很普遍不好啓動動畫在OnCreate方法。我從來沒有親自需要這樣做,但我已閱讀的共識說,要在onWindowFocusChanged方法中執行此操作。

+0

@Whitney ....感謝這個地方,我最初把對象當作'local',當我把它變成'global'時,我忘記了也刪除了'local'對象的創建。它現在可以工作,也感謝關於'onWindowFocusChanged'的提醒,我還沒有意識到這一點,因爲我還是Android新手。 – user94628 2014-09-11 18:43:41

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 
+0

如果您需要動畫無限運行,該怎麼辦? – user94628 2014-09-11 13:12:21