Advertisement
GGGG2468

Counter

Jan 30th, 2023
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. activity_main.xml
  2.  
  3.  
  4. <?xml version="1.0" encoding="utf-8"?>
  5. <LinearLayout
  6.  xmlns:android="http://schemas.android.com/apk/res/android"
  7.  xmlns:tools="http://schemas.android.com/tools"
  8.  android:layout_width="match_parent"
  9.  android:layout_height="match_parent"
  10.  tools:context=".MainActivity"
  11.  tools:ignore="Deprecated">
  12.  <TextView
  13.  android:id="@+id/idDisplay"
  14.  android:layout_width="181dp"
  15.  android:layout_height="40dp"
  16.  android:layout_x="16dp"
  17.  android:layout_y="16dp"
  18.  android:gravity="center"
  19.  android:hint="press start to begin"/>
  20.  <Button
  21.  android:id="@+id/idStart"
  22.  android:layout_width="wrap_content"
  23.  android:layout_height="wrap_content"
  24.  android:layout_x="16dp"
  25.  android:layout_y="61dp"
  26.  android:text="start"/>
  27.  <Button
  28.  android:id="@+id/idStop"
  29.  android:layout_width="wrap_content"
  30.  android:layout_height="wrap_content"
  31.  android:layout_x="110dp"
  32.  android:layout_y="61dp"
  33.  android:text="stop"/>
  34. </LinearLayout>
  35.  
  36. MainActivity.java
  37.  
  38.  
  39. package com.example.program5;
  40. import android.os.Bundle;
  41. import android.view.View;
  42. import android.os.Handler;
  43. import android.os.Message;
  44. import android.widget.Button;
  45. import android.widget.TextView;
  46. import androidx.appcompat.app.AppCompatActivity;
  47. public class MainActivity extends AppCompatActivity implements View.OnClickListener, Runnable {
  48.  Thread th;
  49.  int count = 0;
  50.  TextView display;
  51.  Button start, stop;
  52.  Boolean isRunning = false;
  53.  @Override
  54.  protected void onCreate(Bundle b) {
  55.  super.onCreate(b);
  56.  setContentView(R.layout.activity_main);
  57.  display = findViewById(R.id.idDisplay);
  58.  start = findViewById(R.id.idStart);
  59.  stop = findViewById(R.id.idStop);
  60.  start.setOnClickListener(this);
  61.  stop.setOnClickListener(this);
  62.  }
  63.  @Override
  64.  public void onClick(View v) {
  65.  if(v.equals(start)){
  66.  isRunning = true;
  67.  th = new Thread(this);
  68.  th.start();
  69.  }
  70.  else if(v.equals(stop)){
  71.  isRunning = false;
  72.  }
  73.  }
  74.  Handler h = new Handler(){
  75.  @Override
  76.  public void handleMessage(Message msg) {
  77.  display.setText(""+msg.what);
  78.  }
  79.  };
  80.  public void run(){
  81.  while(isRunning){
  82.  try {
  83.  Thread.sleep(1000);
  84.  } catch (InterruptedException e) {
  85.  e.printStackTrace();
  86.  }
  87.  count++;
  88.  h.sendEmptyMessage(count);
  89.  }
  90.  }
  91. }
  92.  
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement