Create a Stopwatch App using Chronometer in Sketchware
To create a Stopwatch App in sketchware using Chronometer, follow the steps given below.
1. Create a new project in Sketchware.
2. In VIEW area add a LinearV with width and height as match_parent, and gravity as center_horizontal, center_vertical.
• Inside this add a LinearH linear2 with width 240, height 240, padding 20, magin 8, and gravity center_horizontal, center_vertical.
• Below linear2, add two Buttons start_button and pause_button. Set their margins as 8 and text as START and PAUSE respectively.
4. In the more block extra, use an add source directly blocks and put codes to declare a long variable timeWhenStopped, and a Chronometer stopclock.
private long timeWhenStopped = 0;
private Chronometer stopclock;
5. Add 5 number variables mode, ZERO, RUNNING, STOPPED, PAUSED.
6. In onCreate event, set ZERO to 0, RUNNING to 1, STOPPED to 2, PAUSED to 3, and mode to ZERO.
After this use an add source directly block and put codes to set a GradientDrawable as background of linear2.
int strokeWidth = 5;
int strokeColor = Color.parseColor("#03dc13"); android.graphics.drawable.GradientDrawable gD = new android.graphics.drawable.GradientDrawable(); gD.setShape(android.graphics.drawable.GradientDrawable.OVAL);
After this use another add source directly block and put codes to define the Chronometer and set it as View of linear2.
stopclock = new Chronometer(this);
After that set the pause_button INVISIBLE.
7. In start_button onClick event, use blocks as shown in image below.
If mode is RUNNING or PAUSED, following code is used to stop the Stopwatch and mode is set to STOPPED and start_button text is set as RESET.
If mode is STOPPED, following code is used to reset the Stopwatch and mode is set to ZERO, and start_button text is set as START.
timeWhenStopped = 0;
8. In pause_button onClick event, use blocks as shown in image below.
Here is mode is RUNNING following code is used to pause the Stopwatch, mode is set to PAUSED and pause_button text is set as RESUME.
timeWhenStopped = stopclock.getBase() - SystemClock.elapsedRealtime();
If mode is PAUSED, following code is used to resume the Stopwatch and mode is set to RUNNING, and pause_button text is set as PAUSE.
stopclock.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
7. Save and Run the project. You will see the stopwatch on the main page. On clicking the start_button it starts, and on clicking the pause_button it stops but can be resumed.
Create Stopwatch app in Android Studio: