1. 程式人生 > >Android webview頁面返回鍵

Android webview頁面返回鍵

設定webview支援js頁面

settings.setJavaScriptEnabled(true);
//設定監聽,攔截url讓介面跳轉只在本app內部跳轉,不跳轉瀏覽器
 web_h5.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != "") {
                    view.loadUrl(url);
                }
                //true,攔截url在本app內進行頁面跳;false,不攔截,會跳到別的瀏覽器
                return true;
            }
        });


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && web_h5.canGoBack()) {
            web_h5.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

 /**
         *
         * 防止遇到重定向
         */
        web_h5.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && web_h5.canGoBack()) {
                        web_h5.goBack();
                        return true;
                    }
                }

                return false;
            }
        });