Advertisement
programusy

Untitled

Oct 13th, 2023
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. import android.os.Bundle;
  2. import android.os.Handler;
  3. import android.support.v7.app.AppCompatActivity;
  4. import android.view.View;
  5. import android.widget.Button;
  6. import android.widget.TextView;
  7.  
  8. public class StoperActivity extends AppCompatActivity {
  9.  
  10. private int seconds = 0;
  11. private boolean running;
  12. private boolean wasRunning;
  13.  
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_stopwatch);
  18. if (savedInstanceState != null) {
  19. seconds = savedInstanceState.getInt("seconds");
  20. running = savedInstanceState.getBoolean("running");
  21. wasRunning = savedInstanceState.getBoolean("wasRunning");
  22. }
  23.  
  24. runTimer();
  25. }
  26.  
  27. @Override
  28. protected void onSaveInstanceState(Bundle savedInstanceState) {
  29. savedInstanceState.putInt("seconds", seconds);
  30. savedInstanceState.putBoolean("running", running);
  31. savedInstanceState.putBoolean("wasRunning", wasRunning);
  32. }
  33.  
  34. public void onClickStart(View view) {
  35. running = true;
  36. }
  37.  
  38. public void onClickStop(View view) {
  39. running = false;
  40. }
  41.  
  42. public void onClickReset(View view) {
  43. running = false;
  44. seconds = 0;
  45. }
  46.  
  47. private void runTimer() {
  48. final TextView timeView = (TextView) findViewById(R.id.time_view);
  49. final Handler handler = new Handler();
  50. handler.post(new Runnable() {
  51. @Override
  52. public void run() {
  53. int hours = seconds / 3600;
  54. int minutes = (seconds % 3600) / 60;
  55. int secs = seconds % 60;
  56. String time = String.format("%d:%02d:%02d", hours, minutes, secs);
  57. timeView.setText(time);
  58.  
  59. if (running) {
  60. seconds++;
  61. }
  62. handler.postDelayed(this, 1000);
  63. }
  64. });
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement