API21
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/timeview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/TIME"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textSize="60sp" />
<Button
android:id="@+id/buttonstart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="onClickstart"
android:text="@string/start" />
<Button
android:id="@+id/buttonstop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="onClickstop"
android:text="@string/stop" />
<Button
android:id="@+id/buttonreset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="onClickreset"
android:text="@string/reset" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
string.xml
<resources>
<string name="app_name">stopwatch</string>
<string name="TIME">0:00;00</string>
<string name="start">start</string>
<string name="stop">stop</string>
<string name="reset">reset</string>
</resources>
Mainactivity.java
package com.e.stopwatch;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int seconds=0;
private boolean running=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runtimer();
}
public void onClickstart(View view){running=true;}
public void onClickstop(View view){running=false;}
public void onClickreset(View view){running=false;seconds=0;}
private void runtimer(){
final TextView timeview=findViewById(R.id.timeview);
final Handler handler=new Handler();
handler.post(new Runnable() {
@Override
public void run() {
int hours=seconds/3600;
int minutes=(seconds%3600)/60;
int secs=seconds%60;
String time=String.format("%d:%02d:02d%",hours,minutes,secs);
timeview.setText(time);
if (running){seconds++;}
handler.postDelayed(this,1000);
}
});
}
}