2015-12-15 30 views
1

我是和Android的新手,我想在我的ACTION_UP事件中設置一個時間計數器,並在我做其他事件時取消計時器。我如何基本上設置一個計時器,並停止並重置其他事件的計時器?我點擊按鈕後如何查看持續時間

+0

你想得到剛開始和結束的時差嗎? –

回答

1

計時器開始時間。

在開始計時器點擊事件中設置此項。

Date startDate = new Date(); 
long startTime = 0; 
startTime = startDate.getTime(); 

在全局變量中存儲startTime,以便稍後使用該變量。

計時器結束時間。

在停止計時器單擊事件中設置此項。

Date endDate = new Date(); 
long endTime = 0; 
endTime = endDate.getTime(); 

現在得到毫秒時間差

long timeDiff = endTime - startTime; 
+0

其實你的方式適合我!感謝您的協助! –

0

你一定要試試這個

public boolean onTouchEvent(MotionEvent event) { 
    boolean touch; 
     switch(event.getAction()){ 
      case MotionEvent.ACTION_DOWN: 
       touch = false; 
       break; 
      case MotionEvent.ACTION_UP: 
       touch = true; 
       // Code for Timer 
       break; 
     } 
    return true; 
    } 

你必須寫在代碼裏的處理器和重置等事件的處理程序。對於處理器

new Handler().postDelayed(new Runnable() { 
     public void run() { 
      //Your Task     
     } 
    }, TIME); 
1

CountDownTimer在這裏,我以毫秒爲單位啓動時股票爲30秒像

CountDownTimer countDownTimer; 
TextView tvTicker = (TextView) findViewById(R.id.tvTicker); 

public void startClicked(View view) { //When button start is clicked 

    countDownTimer = new CountDownTimer(30000, 1000) { 

     public void onTick(long millisUntilFinished) { 
      tvTicker.setText("seconds remaining: " + millisUntilFinished/1000); 
//Do some stuff here for saving the duration to a variable or anything else as your requirements 
     } 

     public void onFinish() { 
      tvTicker.setText("done!"); 
     } 
    }.start(); 
} 

方法說明

CountDownTimer(long millisInFuture, long countDownInterval) 

millisInFuture = 時間 代碼

countDownInterval = 間隔,單位爲毫秒

現在你可以使用這些方法對於其他類型的操作。

countDownTimer.cancel(); //Cancel the countdown. 
countDownTimer.onFinish() //Callback fired when the time is up. 
countDownTimer.onTick(long millisUntilFinished); //Callback fired on regular `interval. millisUntilFinished is The amount of time until finished.` 
+0

您的解決方案有效,非常感謝!你剛剛救了我的一天! –

相關問題