0

I am designing a simple app in which myfunction() is called when the start button is pressed. myfunction() takes a few seconds to complete. Right now when I press the Start Button, myfunction() runs for a few seconds and after it is complete, the text of the button changes to "Stop". I want the text of the button to change to "Stop" as soon as the "Start" Button is pressed and before the function is called.

This is my first time working with Android Studio and Java. Any help is appreciated.

I've attached the function which is called when the button is pressed.

public void buttonClick(View v) {
    Button tv = (Button)findViewById(R.id.button1);
    if(tv.getText() == "Start") {
        tv.setText("Stop");
        myfunction();
    }
    else {
        tv.setText("Start");
    }
}
Anonymous
  • 1
  • 1
  • If you put text-changing code to the first line of the `myfunction()`, it will work! – Omid.N May 15 '20 at 17:26
  • you should run your `myfunction()` in a thread so that you don't block the UI. check this https://stackoverflow.com/a/31549559/178280 . Also I understand that you are learning to code so try not to use the button text to compare the state. You should define a variable and decide what text to be displayed based on that variable. – grassyburrito May 15 '20 at 17:32

2 Answers2

2

Don't use tv.getText()=="Start" use tv.getText().equals("Start") like this...

public void buttonClick(View v) {
    Button tv = (Button)findViewById(R.id.button1);
    if(tv.getText().equals("Start")) {
        tv.setText("Stop");
        myfunction();
    }
    else {
        tv.setText("Start");
    }
}
AgentP
  • 6,261
  • 2
  • 31
  • 52
0

to use the equals, do something like :

 public void buttonClick(View v) {
    Button tv = (Button)findViewById(R.id.button1);
    if(tv.getText().toString() == "Start") {
        tv.setText("Stop");
        myfunction();
    }
    else {
        tv.setText("Start");
    }
}
ochieng seth
  • 59
  • 1
  • 14