1

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?

theblitz
  • 6,683
  • 16
  • 60
  • 114

2 Answers2

1

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);
    }
}
josh527
  • 6,971
  • 1
  • 19
  • 19
1

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.

N-JOY
  • 10,344
  • 7
  • 51
  • 69
  • What happens when the loop finishes before all the messages are done. I assume control just continues on. – theblitz Jun 05 '11 at 11:01
  • of course the loop finishes before call comes to handler. what this code actually does is it queues all the messages and schedule them after 2 sec., 4 sec., 6 sec., 8 sec.. after 2 seconds, 46, 8 sec android itself calls method handlemessage, where we wrote code for toast – N-JOY Jun 05 '11 at 11:12