public class MainActivity extends AppCompatActivity { private long startTime; private long elapsedTime = 0l; private Handler handler = new Handler(); private Runnable updateTimer; private Button startButton; private Button stopButton; private Button resetButton; private TextView timerLabel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startButton = (Button) findViewById(R.id.startButton); stopButton = (Button) findViewById(R.id.stopButton); resetButton = (Button) findViewById(R.id.resetButton); timerLabel = (TextView) findViewById(R.id.timerLabel); setButtonState(true,false,false); } public void setButtonState(boolean start, boolean stop, boolean reset){ startButton.setEnabled(true); stopButton.setEnabled(false); resetButton.setEnabled(false); } public void startTimer(View view){ // startTimeの取得 startTime = SystemClock.elapsedRealtime(); // 起動してからの経過時間(ミリ秒) // 一定時間ごとに現在の経過時間を表示 // handler -> Runnable(処理) -> UI updateTimer = new Runnable(){ @Override public void run(){ long t = SystemClock.elapsedRealtime() - startTime + elapsedTime; SimpleDateFormat sdf = new SimpleDateFormat("mm:ss.SSS", Locale.US); timerLabel.setText(sdf.format(t)); handler.removeCallbacks(updateTimer); handler.postDelayed(updateTimer, 10); } }; handler.postDelayed(updateTimer, 10); // ボタンの操作 setButtonState(false, true, false); } public void stopTimer(View view){ elapsedTime += SystemClock.elapsedRealtime() - startTime; handler.removeCallbacks(updateTimer); setButtonState(true,false, true); } public void resetTimer(View view){ elapsedTime = 0; timerLabel.setText("00:00.000"); setButtonState(true,false, false); } }
runnable、SimpleDateFormat、removeCallbacks、handlerがよくわからんな。