Send a number of "Toast"s spaced by 2 seconds
I need to display 4 "Toast"s spaced by 2 seconds between them.
How do I do this in such a way that开发者_如何学运维 they wait for each other and that the program itself waits until the last of them has displayed?
simply use handlers.
handler has a method called sendMessageDelayed(Message msg, long delayMillis).
just schedule your messages at the interval of 2 seconds.
here is a sample code.
int i=1;
while(i<5){
Message msg=Message.obtain();
msg.what=0;
hm.sendMessageDealayed(msg, i*2);
i++;
}
now this code will call handler's method handleMessage after every 2 seconds.
here is your Handler
Handler hm = new Handler(){
public void handleMessage(Message msg)
{
//Toast code.
}
};
and you are done.
Thanks.
Handlers are definitely the way to go but I would just postDelayed instead of handling an empty message.
Also extending Toast and creating a method for showing it longer is nice.
Sample Code:
// make sure to declare a handler in the class
private final Handler mHandler = new Handler();
// The method to show longer
/**
* Show the Toast Longer by repeating it.
* Depending upon LENGTH_LONG (3.5 seconds) or LENGTH_SHORT (2 seconds)
* - The number of times to repeat will extend the length by a factor
*
* @param number of times to repeat
*/
public void showLonger(int repeat) {
// initial show
super.show();
// to keep the toast from fading in/out between each show we need to check for what Toast duration is set
int duration = this.getDuration();
if (duration == Toast.LENGTH_SHORT) {
duration = 1000;
} else if (duration == Toast.LENGTH_LONG) {
duration = 2000;
}
for (int i = 1; i <= repeat; i++) {
// show again
handler.postDelayed(new Runnable() {
@Override
public void run() {
show();
}
}, i * duration);
}
}
精彩评论