2017-05-08 93 views
0

好吧,所以,我正在嘗試使用onClick()函數的每個觸發器來計數上/下計數器。事情是我希望它在X時間過去時加快計數。Android按下按鈕,加速計數

我覺得這樣的事情應該工作:

Button button = new Button(context); 
button.setOnTouchListener(new RepeatListener(1, 1, new OnClickListener() { 

    @Override 
    public void onClick(View view) { 
    /* 
     count++; 
     wait for some amount of time, lets call it timeX; 
     if(timeX !< 100){ 
     timeX -= 10; 
     } 
    */ 
    } 
})); 

但我敢肯定,必須有什麼,我試圖做一個功能。

是的,在你評論它之前,初始和重複間隔是相同的。我希望它能夠加速,具體取決於你維持多長時間按下按鈕/按下的任何按鈕,直到當然。

任何想法,我如何可以使它或我應該使用哪個函數?我可以在我以前的代碼中循環「for」,但必須有其他方法。我有點新到Android/Java的:P

回答

0

你可以添加一個觸摸監聽器中,你可以得到,當按下按鈕上ACTION_DOWN當例如發佈ACTION_UP

long lastPressed; 
    long duration; 

    button.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     if(event.getAction() == MotionEvent.ACTION_DOWN) { 
      //button pressed save the time 
      lastPressed = System.currentTimeMillis(); 
     } 
     else if (event.getAction() == MotionEvent.ACTION_UP) { 
      //button released calculate the time 
      duration = System.currentTimeMillis() - lastPressed; 
     } 
    } 
    });