user6463207 user6463207 - 5 months ago 8
Android Question

Is it possible to make a "wait seconds" function in Android?

I wanna make a function for waiting 2 seconds, and then doing something (display a text).

Is there any way to do that? Thanks

I post the code, and if you can tell me if it is possible...

Code where I wanna put it (it's commented)

case (R.id.addPoints1):

if(restar){

pp1 = pp1 - 1;
playerPoints1.setText(Integer.toString(pp1));
restar = false;

} else {

pp1 = pp1 + 1;
playerPoints1.setText(Integer.toString(pp1));

}

if(pp1 == 10){

String messageString = "10 punts! Agafa la foto de la ciutat";
//Toast.makeText(getApplicationContext(), "10 punts! Agafa la foto de la ciutat", Toast.LENGTH_LONG);
Snackbar message = Snackbar.make(findViewById(R.id.myLinearLayout), messageString, Snackbar.LENGTH_LONG);
message.show();
pp1 = 0;

//WAIT 2 SECONDS
playerPoints1.setText(Integer.toString(pp1));
}
break;

case (R.id.addPoints2):

if(restar){

pp2 = pp2 - 1;
playerPoints2.setText(Integer.toString(pp2));
restar = false;

}else {

pp2 = pp2 + 1;
playerPoints2.setText(Integer.toString(pp2));

}

if(pp2 == 10){

String messageString = "10 punts! Agafa la foto de la ciutat";
//Toast.makeText(getApplicationContext(), "10 punts! Agafa la foto de la ciutat", Toast.LENGTH_LONG);
Snackbar message = Snackbar.make(findViewById(R.id.myLinearLayout), messageString, Snackbar.LENGTH_LONG);
message.show();
pp2 = 0;

//WAIT 2 SECONDS
playerPoints2.setText(Integer.toString(pp2));
}
break;

case (R.id.addPoints3):

if(restar){

pp3 = pp3 - 1;
playerPoints3.setText(Integer.toString(pp3));
restar = false;

}else {

pp3 = pp3 + 1;
playerPoints3.setText(Integer.toString(pp3));

}

if(pp3 == 10){

String messageString = "10 punts! Agafa la foto de la ciutat";
//Toast.makeText(getApplicationContext(), "10 punts! Agafa la foto de la ciutat", Toast.LENGTH_LONG);
Snackbar message = Snackbar.make(findViewById(R.id.myLinearLayout), messageString, Snackbar.LENGTH_LONG);
message.show();
pp3 = 0;

//WAIT 2 SECONDS
playerPoints3.setText(Integer.toString(pp3));

}
break;

case (R.id.addPoints4):

if(restar == true){

pp4 = pp4 - 1;
playerPoints4.setText(Integer.toString(pp4));
restar = false;

}else {

pp4 = pp4 + 1;
playerPoints4.setText(Integer.toString(pp4));

}

if(pp4 == 10){

String messageString = "10 punts! Agafa la foto de la ciutat";
//Toast.makeText(getApplicationContext(), "10 punts! Agafa la foto de la ciutat", Toast.LENGTH_LONG);
Snackbar message = Snackbar.make(findViewById(R.id.myLinearLayout), messageString, Snackbar.LENGTH_LONG);
message.show();
pp4 = 0;

//WAIT 2 SECONDS
playerPoints4.setText(Integer.toString(pp4));

}
break;
}


Thanks again!

Answer

Try something like this..

new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // call your function
            }
        }, 2000);