public class MainActivity extends AppCompatActivity {
private Button my_button;
private boolean start_stop = false;
private int counter = 0;
private TextView my_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_button = findViewById(R.id.My_Button);
my_text = findViewById(R.id.my_text);
}
public void onClick_button(View view) {
if(start_stop != true) {
my_button.setText("STOP");
start_stop = true;
runOnUiThread(new Runnable() {
@Override
public void run() {
while (start_stop) {
my_text.setText(Integer.toString(counter));
counter++;
try {
Thread.sleep(1000); // sleep 1 sec
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}else {
my_button.setText("START");
start_stop = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
start_stop = false;
}
package com.example.switch_pictures;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button my_button;
private boolean start_stop = false;
private int counter = 0;
private TextView my_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_button = findViewById(R.id.My_Button);
my_text = findViewById(R.id.my_text);
}
public void onClick_button(View view) {
if(start_stop != true) {
my_button.setText("STOP");
start_stop = true;
new Thread(new Runnable() {
@Override
public void run() {
while (start_stop) {
runOnUiThread(new Runnable() {
@Override
public void run() {
my_text.setText(Integer.toString(counter));
}
});
counter++;
try {
Thread.sleep(100); // sleep 1 sec
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}else {
my_button.setText("START");
start_stop = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
start_stop = false;
}
}