Android 上多次显示同一个 Toast 正常吗?

问题描述 投票:0回答:3

我使用

Toast
向用户显示一些信息,因为我想立即显示最新消息,而不管以前的消息如何,我这样做(从旧项目中学到):

public class MainActivity extends Activity {

    private Toast mToast;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    }

    private void toast(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.setText(message);
                mToast.show();
            }
        });
    }
}

也就是说,单个

Toast
对象被重复使用并显示多次,每当我需要显示新消息时,我只需再次
setText
show
即可。看起来工作正常,但是当我在 Google 上搜索后,我发现大多数人都会这样做:

    private void toast(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mToast.cancel();
                mToast = Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT);
                mToast.show();
            }
        });
    }

其中

cancel
是之前的 Toast,然后通过
Toast.makeText
制作一个新的 Toast。

有什么不同吗?我应该选择哪一个?

android android-toast
3个回答
1
投票

您可以将当前的 Toast 缓存在 Activity 的变量中,然后在显示下一个 Toast 之前取消它。这是一个例子:

Toast m_currentToast;

void showToast(String text)
{
    if(m_currentToast != null)
    {
        m_currentToast.cancel();
    }
    m_currentToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    m_currentToast.show();

}

另一种即时更新Toast消息的方法:

void showToast(String text)
{
    if(m_currentToast == null)
    {   
        m_currentToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    }

    m_currentToast.setText(text);
    m_currentToast.setDuration(Toast.LENGTH_LONG);
    m_currentToast.show();
}

参考:如何立即用第二个Toast替换当前的Toast而不等待当前的Toast完成?


0
投票

您应该尝试类似这样的代码,以避免一次看到多个 toast。

 private void toast(final String message) {
 try{ mToast.getView().isShown();     // true if visible
        mToast.setText(message);
    } catch (Exception e) {         // invisible if exception
        mToast = Toast.makeText(theContext, message, toastDuration);
        }
    mToast.show();  //finally display it
}

帮助我的代码是这里


0
投票

首先,您必须为您的Toast创建函数并根据您的要求使用该函数。

© www.soinside.com 2019 - 2024. All rights reserved.