0

I want my app to wait for a moment before changing the button text. I tried different things (wait(), Thread.sleep) but since I want the waiting time to be variable, I decided to make use of CountDownTimer. See the code below:

  public void onClick(View buttonClicked) {
    if (i == 0) {
        button.setText("Wait");
        waitingTime = (long) (Math.random() * 1000 + 10000);
        new countdown(waitingTime, 1000);
        time1 = System.currentTimeMillis();
        button.setText("Press");
        i++;

For some reason this doesn´t work, and the program does not wait at all. Can anyone please help me? I did not fill the CountDownTimer with anything since I figured that it should only wait for a couple of seconds.

Rob
  • 15
  • 1
  • 5

2 Answers2

0

Thread is also variable:

try {
 Thread.sleep(1000);
 } catch (Exception e) {
 }
silvia_aut
  • 1,481
  • 6
  • 19
  • 33
0

try this code

@Override
public void onClick(View view) {
if(i==0) {
        YourActivity.this.runOnUiThread(new Runnable() {



@Override               

public void run() {
txtView.setText("please wait...");
}
});

while(counter < 1000) {
try {
    Thread.sleep(100);
}catch(InterruptedException e) {
    e.printStackTrace();
}
counter +=100;
}

txtView.setText("press");


i++;


}

}

Increase the thread timing according to ur needs. And if needed write this code in the function where you are passing the sleep value

EDIT

mHandler = new Handler(); btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
            btn.setText("wait");
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    btn.setText("press");
                }
            }, 1500);
        }
    });
  • I used the Thread.sleep and it does wait but not the text on the button isn´t changed... How can I show my code correctly? > public void onClick(View buttonClicked) { button.setText("Wait"); if (i == 0) { waitingTime = (long) (Math.random() * 1000 + 3000); try { Thread.sleep(waitingTime); } catch (Exception e) { } time1 = System.currentTimeMillis(); button.setText("Press"); i++; – Rob Oct 22 '13 at 12:43
  • YourActivity.this.runOnUiThread(new Runnable() { @Override public void run() { button.setText("Wait"); } }); try this instead of just button.setText("Wait"); – Rat-a-tat-a-tat Ratatouille Oct 22 '13 at 12:44
  • look at [this](http://stackoverflow.com/questions/2300169/how-to-change-text-in-android-textview?answertab=votes#tab-top) – Rat-a-tat-a-tat Ratatouille Oct 22 '13 at 13:03