依次显示多个Toast的问题

Problem with display multiple Toast in order one after another

抱歉我的英语不好。
我想按顺序显示两个吐司,换句话说,当第一个吐司持续时间结束时,第二个吐司出现。
这是我的代码:

Toast.makeText(this, "Toast1", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Toast2", Toast.LENGTH_SHORT).show();

但只会出现第二条消息。我想当第二个 toast 的 show 方法执行时它会取消之前的 toast(第一个 toast)

我用这段代码解决了我的问题:

Toast.makeText(this, "Toast1", Toast.LENGTH_SHORT).show();
    Handler handler =new Handler();
    handler.postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            Toast.makeText(MainActivity.this, "Toast2", Toast.LENGTH_SHORT).show();
        }
    },1000);

但是有没有更简单的解决方案?

有两种实现方式

  • 方法1:像以前一样使用Thread,但使用timer并执行一个 一个
  • 方法二:使用任意循环,例如使用For循环

这应该对您有所帮助:

Toast.makeText(this, "Show toast 1", Toast.LENGTH_SHORT).show();
    new Thread(){
        @Override
        public void run() {
            try{
                sleep(Toast.LENGTH_SHORT); // sleep the time first toast is being shown
                Toast.makeText(this, "Show toast 2", Toast.LENGTH_SHORT).show();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }.start();

but only second toast message will appear. i think when show method of second toast will execute it will cancel previous toast (first toast)

当调用show方法时,会放入UI线程的消息队列,Toast会按顺序显示。但是你同时放两个Toast,后者会和前者重叠。

i want show two toast in order, in other word when first toast duration is over second toast appear.

来自Toast duration

private static final int LONG_DELAY = 3500; // 3.5 seconds 
private static final int SHORT_DELAY = 2000; // 2 seconds

要在第一个吐司结束后显示第二个吐司,请将代码更改为

Toast.makeText(this, "Toast1", Toast.LENGTH_SHORT).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
    @Override
    public void run()
    {
        Toast.makeText(MainActivity.this, "Toast2", Toast.LENGTH_SHORT).show();
    }
}, 2000);

but is there any easier solution?

使用 Handler 是完成任务的简单易行的解决方案。

其他解决方案是使用 AlertDialog

createDialog().show();

有两个方法 createDialog() 和 continueDialog()

public AlertDialog createDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Toast1")
            .setPositiveButton("Next",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            continueDialog().show();
                        }
                    });
    return builder.create();
}

public AlertDialog continueDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Toast2")
            .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
    return builder.create();
}