user3476090 user3476090 - 22 days ago 6
Java Question

Three onClick actions on one button at same time

I develop a program that does when i click on a button that starts counting the clicks and show the count and after 5 seconds that button is desible and i want show countdown seconds too but it not showing

mTextView = (TextView) findViewById(R.id.total_textview);
mTextView.setVisibility(View.VISIBLE);

Button button = (Button) findViewById(R.id.count_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
final Button b = (Button)v;
if (clicks == 0){
// Means its the first time that a user click the button
// Start a thread that is going to disable the button after 5 seconds from first click
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
@Override
public void run() {
b.setText("Time up");
b.setEnabled(false);
// Showing user clicks after button is disabled
showClicks();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
// Here we are just counting . . . . including the first click
countClicks();
}
});
}


private void countClicks(){
++clicks;
mTextView.setText(Integer.toString(clicks));

// You can update your text view here
}
private void showClicks(){
mTextView.setText(String.valueOf(clicks)+"Clicks");
mTextView.setVisibility(View.VISIBLE);

}


}

Answer

I suggest you take a look at CountDownTimer.

Here your modified code which updates UI. It ticks ever 1 second and updates a TextView for 5 seconds. At the end, it says "Time up":

new CountDownTimer(5000, 1000) {

     public void onTick(long millisUntilFinished) {
         b.setText("Seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         b.setText("Time up");
         b.setEnabled(false);
         // Showing user clicks after button is disabled
         showClicks();
     }
  }.start();