只有当它与现有的吐司不同时才显示吐司

时间:2016-08-07 22:35:50

标签: java android android-toast

所以我的目标是,如果没有显示Toast消息或者显示的消息与我要发送的消息不同,则只向用户显示Toast消息。如果消息与向用户显示的消息相同,我不希望消息通过(因为这是毫无意义的)。

为了实现这一目标,我发现了this帖子,了解如何只显示祝酒词。

我修改了代码以满足这两个要求。

private Toast toast;

public void showAToast (String st, boolean isLong){
    try{
        toast.getView().isShown();
        String text = ((TextView)((LinearLayout)toast.getView()).getChildAt(0)).getText().toString();
        if(!text.equalsIgnoreCase(st)){
            //New message, show it after
            if(isLong){
                toast = Toast.makeText(getApplicationContext(), st, Toast.LENGTH_LONG);
            } else {
                toast = Toast.makeText(getApplicationContext(), st, Toast.LENGTH_SHORT);
            }
            toast.show();
        }
    } catch (Exception e) {
        //New message
        if(isLong){
            toast = Toast.makeText(getApplicationContext(), st, Toast.LENGTH_LONG);
        } else {
            toast = Toast.makeText(getApplicationContext(), st, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}

我的问题是,如果最后一个Toast消息与想要通过的消息相同,则任何消息都不会通过。

不确定为什么会发生这种情况,但我在方法中放了一些调试信息来弄清问题是什么。

消息说toast.getView()。isShown()如果在应用程序的生命周期内发送了任何Toast消息,则不会抛出异常(假设没有显示toast)。

所以我的问题是,我该如何解决这个问题?当然必须有一种方法来实现这种所需的功能。

2 个答案:

答案 0 :(得分:0)

我之前在stackoverflow中看过这个,但它并不像我希望的那样干净。我们实施了双重吐司方法,它在两个吐司之间交替进行。首先,我们在OnCreate之前定义活动的祝酒词:

Toast toast0;
    Toast toast1;
    private static boolean lastToast0 = true;
    In the OnCreate:

    toast0 = new Toast(getApplicationContext());
    toast0.cancel();
    toast1 = new Toast(getApplicationContext());
    toast1.cancel();
    //And finally, when I need to display the toast and cancel the prior toast at the same time I use something similar to:

            if (lastToast0) {
                toast0.cancel();
                toast1.setDuration(Toast.LENGTH_LONG);
                toast1.setText("new message");
                toast1.show();
                lastToast0 = false;
            } else {
                toast1.cancel();
                toast0.setDuration(Toast.LENGTH_LONG);
                toast0.setText("new message");
                toast0.show();
                lastToast0 = true;
            }
   // If you need to just cancel an existing toast (before it times out) use:

                toast0.cancel();
                toast1.cancel();

<强>报价

答案 1 :(得分:0)

您可以使用相同的Toast实例来显示消息。如果消息相同,则toast将不会显示两次,否则文本将简单地更改为最新的。

Toast mToast;

public void showToast(CharSequence message, int during){
    if (mToast == null) {
        mToast = Toast.makeText(getApplicationContext(), message, during);
    } else {
        mToast.setText(message);
    }
    mToast.show();
}

- ↓↓--- ---- ---↓↓update-- ---- ---↓↓ - ↓

很抱歉,我错过了你的观点。

我读了Toast的源代码,因为视图已经添加到WindownManager,我们无法获得视图状态。到目前为止,我找不到指出是否显示Toast的方法。

但您可以实现自己的Toast use Service,它喜欢在应用程序上方显示的Toast。它可能更容易。

相关问题