按下后退按钮时,Android webview将关闭

时间:2016-03-23 13:48:01

标签: android webview onkeydown

这是我WebView的代码。 WebView正确运行,但按下后退按钮时出现问题:应用关闭。

   @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        //enable layout
        setContentView(R.layout.activity_main);

        //create istance webview
        WebView myWebView = (WebView) findViewById(R.id.webview);

        //initialize webview's settings
        WebSettings webSettings = myWebView.getSettings();

        //enable javascript
        webSettings.setJavaScriptEnabled(true);

        //load image
        webSettings.setLoadsImagesAutomatically(true);

        //inizialize client
        MyWebViewClient myWebViewClient = new MyWebViewClient();

        //set webview to client
        myWebView.setWebViewClient(myWebViewClient);

        //load website by URL
        myWebView.loadUrl(website_url);

        this.onStart();
    }
    @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) && myWebView.canGoBack()) {
            myWebView.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);
    }
}

崩溃日志

03-23 14:43:18.530 14051-14051/com.quogito.quogito W/UnimplementedWebViewApi: Unimplemented WebView method onKeyDown called from: android.webkit.WebView.onKeyDown(WebView.java:2319)
03-23 14:43:18.620 14051-14051/com.quogito.quogito E/InputEventSender: Exception dispatching finished signal.
03-23 14:43:18.620 14051-14051/com.quogito.quogito E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
03-23 14:43:18.620 14051-14051/com.quogito.quogito E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.webkit.WebView.canGoBack()' on a null object reference
at com.quogito.quogito.MainActivity.onBackPressed(MainActivity.java:113)
at android.app.Activity.onKeyUp(Activity.java:2497)

2 个答案:

答案 0 :(得分:1)

试试这个

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

答案 1 :(得分:0)

您在此行的myWebView方法中隐藏了onCreate对象:

WebView myWebView = (WebView) findViewById(R.id.webview);

表示永远不会设置名为myWebView的全局变量。

onCreate内的行改为:

myWebView = (WebView) findViewById(R.id.webview);

那么它应该可以正常工作。