当通过webview打开新链接时,Android Webview,后退按钮不起作用

时间:2015-10-16 19:45:58

标签: android webview android-webview back-button android-websettings

我有一个带有本地html,css和javasccript文件的android应用程序。

其中一个页面包含一个图像列表,这些图像有一个链接到附加到它们的外部网站。

每当我点击链接时,都会在网页浏览中打开该网址。但是,当我单击后退按钮时,它不会返回到上一页。

它适用于除使用外部链接的页面之外的所有页面。

MainActivity.java如下所示:

public class MainActivity extends Activity {

WebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    mWebView.loadUrl("file:///android_asset/www/index.html");

    // Enable Javascript
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mWebView.setWebViewClient(new WebViewClient());
    // Force links and redirects to open in the WebView instead of in a browser
}

@Override
public void onBackPressed() {
    if(mWebView.canGoBack()) {
        mWebView.goBack();
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // Check if the key event was the Back button and if there's history
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        mWebView.goBack();
        return true;
    }
    // If it wasn't the Back key or there's no web page history, bubble up to the default
    // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event);
}

}

MyAppWebViewClient.java如下所示:

public class MyAppWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (Uri.parse(url).getHost().equals("/menu")) {
        return true;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    view.getContext().startActivity(intent);
    return true;
}

}

1 个答案:

答案 0 :(得分:0)

看看我在我的应用程序中做了什么,你也可以使用它......

@Override
    public void onBackPressed() {

        if (webView.canGoBack()) {

            webView.goBack();

        } else {
            if (backPressed) {
                super.onBackPressed();
                return;
            }

            this.backPressed = true;
            Toast.makeText(this, "Press Back One More Time To Exit", Toast.LENGTH_SHORT).show();

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

                @Override
                public void run() {
                    backPressed = false;
                }
            }, 2000);

        }

    }

在此代码中,如果您的webView可以返回,它将返回但是如果它不能出现要求用户再次按回退出以防止意外后退....

Handler.postDelayed()用于设置2秒的时间限制....两秒后再次提示用户按下....