Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.timecounter;
- import androidx.appcompat.app.AppCompatActivity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.widget.TextView;
- import android.widget.Toast;
- public class MainActivity extends AppCompatActivity {
- TextView tvTimer;
- Handler handler;
- Runnable runnable;
- int seconds;
- int start;
- int end;
- int step;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- tvTimer = findViewById(R.id.tvTimer);
- // count up
- start = 0;
- end = 10;
- step = 1;
- // count down
- //start=10;
- //end =0;
- //step=-1;
- seconds = start;
- tvTimer.setText(seconds + "");
- handler = new Handler();
- runnable = new Runnable() {
- @Override
- public void run() {
- makeStep();
- if (step > 0) {
- // counting up
- if (seconds >= end) {
- Toast.makeText(MainActivity.this, "Time Over", Toast.LENGTH_SHORT).show();
- } else
- handler.postDelayed(runnable, 1000);
- } else {
- // counting down
- if (seconds <= end) {
- Toast.makeText(MainActivity.this, "Time Over", Toast.LENGTH_SHORT).show();
- } else
- handler.postDelayed(runnable, 1000);
- }
- }
- };
- handler.postDelayed(runnable, 1000);
- }
- public void makeStep() {
- seconds = seconds + step;
- tvTimer.setText(seconds + "");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement