Attribute | Value |
---|---|
layout_width | match_parent |
layout_height | match_parent |
orientation | vertical |
padding | 16dp |
Attribute | TextView | Button1 | Button2 | Button3 |
---|---|---|---|---|
id | txt_time | |||
layout_width | wrap_content | wrap_content | wrap_content | wrap_content |
layout_height | wrap_content | wrap_content | wrap_content | wrap_content |
layout_gravity | center_horizontal | center_horizontal | center_horizontal | center_horizontal |
layout_marginTop | 20dp | 8dp | 8dp | |
textSize | 80sp | 80sp | 25sp | 25sp |
text | 0:00:00 | Start | Stop | Reset |
onClick | onClickStart | onClickStop | onClickReset |
String Name | String Value |
---|---|
start_time | 0:00:00 |
start_caption | Start |
stop_caption | Stop |
reset_caption | reset |
public void onClickStart(View view) { running = true; } public void onClickStop(View view) { running = false; } public void onClickReset(View view) { running = false; seconds = 0; }
private void runTimer( ) { final TextView timeView = findViewById(R.id.time); final Handler handler = new Handler( ); handler.post(new Runnable( ) { @Override public void run( ) { int hours = seconds / 3600; int minutes = (seconds % 3600) / 60; int secs = seconds % 60; String formattedTime = String.format( "%d:%02d:%02d", hours, minutes, secs); timeView.setText(formattedTime); if (running) { seconds++; } handler.postDelayed(this, 1000); } }); }
// Was the stopwatch running before the activity was paused? private boolean wasRunning;
if (savedInstanceState != null) { seconds = savedInstanceState.getInt("seconds"); running = savedInstanceState.getBoolean("running"); wasRunning = savedInstanceState.getBoolean("wasRunning"); }
@Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putInt("seconds", seconds); savedInstanceState.putBoolean("running", running); savedInstanceState.putBoolean("wasRunning", wasRunning); } @Override protected void onPause( ) { super.onPause( ); wasRunning = running; running = false; } @Override protected void onResume( ) { super.onResume( ); if (wasRunning( )) { running = true; } }