使用" onBackPressed"

时间:2018-04-12 16:19:21

标签: android webview alertdialog void onbackpressed

我有这段代码:

public void onBackPressed(){
    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Are you sure you want to exit ?");
    builder.setCancelable(true);
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.cancel();
        }
            });
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
        }
            });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

如果按一次按钮,如何在webview中返回,如果按两次则显示对话框?

3 个答案:

答案 0 :(得分:0)

尝试这样的事情:

boolean backPressed = false;

@Override
public void onBackPressed() {
    if (backPressed) {
        super.onBackPressed();
        //Show your Dialog here
    }

    this.backPressed = true;

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            backPressed = false;                       
        }
    }, /* Delay between successive presses here*/);
} 

答案 1 :(得分:0)

只需使用布尔值即可知道对话框当前是否显示。这是最简单,最干净的方法。

答案 2 :(得分:0)

既然你提到了WebView,你可以考虑这个:

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        // show dialog as before
    }
} 

这样您可以根据需要经常返回webview,然后在到达第一页时显示对话框。