Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- activity_main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity"
- tools:ignore="Deprecated">
- <TextView
- android:id="@+id/idDisplay"
- android:layout_width="181dp"
- android:layout_height="40dp"
- android:layout_x="16dp"
- android:layout_y="16dp"
- android:gravity="center"
- android:hint="press start to begin"/>
- <Button
- android:id="@+id/idStart"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_x="16dp"
- android:layout_y="61dp"
- android:text="start"/>
- <Button
- android:id="@+id/idStop"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_x="110dp"
- android:layout_y="61dp"
- android:text="stop"/>
- </LinearLayout>
- MainActivity.java
- package com.example.program5;
- import android.os.Bundle;
- import android.view.View;
- import android.os.Handler;
- import android.os.Message;
- import android.widget.Button;
- import android.widget.TextView;
- import androidx.appcompat.app.AppCompatActivity;
- public class MainActivity extends AppCompatActivity implements View.OnClickListener, Runnable {
- Thread th;
- int count = 0;
- TextView display;
- Button start, stop;
- Boolean isRunning = false;
- @Override
- protected void onCreate(Bundle b) {
- super.onCreate(b);
- setContentView(R.layout.activity_main);
- display = findViewById(R.id.idDisplay);
- start = findViewById(R.id.idStart);
- stop = findViewById(R.id.idStop);
- start.setOnClickListener(this);
- stop.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- if(v.equals(start)){
- isRunning = true;
- th = new Thread(this);
- th.start();
- }
- else if(v.equals(stop)){
- isRunning = false;
- }
- }
- Handler h = new Handler(){
- @Override
- public void handleMessage(Message msg) {
- display.setText(""+msg.what);
- }
- };
- public void run(){
- while(isRunning){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- count++;
- h.sendEmptyMessage(count);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement