简体   繁体   English

退出android webview应用程序时如何显示弹出消息

[英]How to show pop-up message when exit android webview app

I just made my first Android webview application. 我刚刚制作了第一个Android Webview应用程序。

It works fine but there's still one thing I'd like to add to the webview: an exit button. 它工作正常,但我想添加到Webview的还有一件事:退出按钮。

How I like to do that: 我喜欢这样做:

When users click on the back button of the phone, they go back to the previous page that they visited. 当用户单击电话的后退按钮时,他们将返回到他们访问的上一页。 Now when they are back on the first page they visited and go back, the app automatically closes. 现在,当他们返回所访问的第一页并返回时,该应用程序将自动关闭。 There I would like to show a pop-up message that says "Are you sure you want to exit?" 在那里,我想显示一条弹出消息,指出“您确定要退出吗?”

How can I display a message like that? 如何显示这样的消息?

My code: 我的代码:

// Open previous opened link from history on webview when back button pressed

@Override
// Detect when the back button is pressed
public void onBackPressed() {
    if(webView.canGoBack()) {
        webView.goBack();
    } else {
        // Let the system handle the back button
        super.onBackPressed();
    }
}

EDIT: I made some changes to my code. 编辑:我对我的代码做了一些更改。 This is the result:: 结果如下:

private Boolean exit = false;
@Override
// Detect when the back button is pressed
public void onBackPressed() {
    if(webView.canGoBack()) {
        webView.goBack();
    }
    else {
        if (exit)
            this.finish();
        else {
            Toast.makeText(this, "Press again to close.",
                Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);
        }    

    // Let the system handle the back button
    super.onBackPressed();
    }
}

Adding a toast in the "else" clause is the correct answer. 正确的答案是在“其他”子句中添加吐司。

Make sure to remove "super.onbackpressed". 确保删除“ super.onbackpressed”。 If you don't do that, you're not giving the user any chance of deciding whether he wants to exit or not. 如果您不这样做,则不会给用户任何机会决定他是否要退出。 The pop-up message will just show up and the app will be closed at the same time. 弹出消息将仅显示,并且该应用将同时关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM