Programming Examples

Android application for stop watch


Create a Stopwatch Application in android which contain  Start, Pause and Stop Button. and also perform the functions. 

Output


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">

<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"/>
<Button
android:id="@+id/btn_start"
android:layout_width="200dp"
android:layout_height="80dp"
android:layout_marginTop="20dp"
android:onClick="startTime"
android:text="Start"/>
<Button
android:id="@+id/btn_stop"
android:layout_width="200dp"
android:layout_height="80dp"
android:layout_marginTop="20dp"
android:onClick="stopTime"
android:text="PAUSE"/>
<Button
android:id="@+id/btn_reset"
android:layout_width="200dp"
android:layout_height="80dp"
android:layout_marginTop="20dp"
android:onClick="restartTime"
android:text="STOP"/>

</LinearLayout>
MainActivity.java

package com.example.stopwatch;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Chronometer;

public class MainActivity extends AppCompatActivity {
Chronometer chronometer;
boolean runninng=false;
private long pauseOffset;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chronometer=findViewById(R.id.chronometer);
}
public void startTime(View v)
{
if(!runninng)
{
chronometer.setBase(SystemClock.elapsedRealtime()-pauseOffset);
chronometer.start();
runninng=true;
}
}
public void stopTime(View v)
{
if(runninng)
{
chronometer.stop();
pauseOffset=SystemClock.elapsedRealtime()-chronometer.getBase();
runninng=false;
}
}
public void restartTime(View v)
{
chronometer.setBase(SystemClock.elapsedRealtime());
}
}
CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad