Advertisement
mmayoub

Timer example

Mar 25th, 2023
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | Software | 0 0
  1. package com.example.timecounter;
  2.  
  3. import androidx.appcompat.app.AppCompatActivity;
  4.  
  5. import android.os.Bundle;
  6. import android.os.Handler;
  7. import android.widget.TextView;
  8. import android.widget.Toast;
  9.  
  10. public class MainActivity extends AppCompatActivity {
  11.     TextView tvTimer;
  12.     Handler handler;
  13.     Runnable runnable;
  14.     int seconds;
  15.     int start;
  16.     int end;
  17.     int step;
  18.  
  19.  
  20.     @Override
  21.     protected void onCreate(Bundle savedInstanceState) {
  22.         super.onCreate(savedInstanceState);
  23.         setContentView(R.layout.activity_main);
  24.  
  25.         tvTimer = findViewById(R.id.tvTimer);
  26.         // count up
  27.         start = 0;
  28.         end = 10;
  29.         step = 1;
  30.  
  31.         // count down
  32.         //start=10;
  33.         //end =0;
  34.         //step=-1;
  35.  
  36.  
  37.         seconds = start;
  38.         tvTimer.setText(seconds + "");
  39.  
  40.         handler = new Handler();
  41.         runnable = new Runnable() {
  42.             @Override
  43.             public void run() {
  44.                 makeStep();
  45.  
  46.                 if (step > 0) {
  47.                     // counting up
  48.                     if (seconds >= end) {
  49.                         Toast.makeText(MainActivity.this, "Time Over", Toast.LENGTH_SHORT).show();
  50.                     } else
  51.                         handler.postDelayed(runnable, 1000);
  52.                 } else {
  53.                     // counting down
  54.                     if (seconds <= end) {
  55.                         Toast.makeText(MainActivity.this, "Time Over", Toast.LENGTH_SHORT).show();
  56.                     } else
  57.                         handler.postDelayed(runnable, 1000);
  58.                 }
  59.             }
  60.         };
  61.         handler.postDelayed(runnable, 1000);
  62.  
  63.     }
  64.  
  65.     public void makeStep() {
  66.         seconds = seconds + step;
  67.         tvTimer.setText(seconds + "");
  68.     }
  69. }
  70.  
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement