0

我有这个代码:

package com.android.m2s;

import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView myWebView = (WebView) findViewById(R.id.wvBrowser);
        myWebView.loadUrl("http://www.message2space.es.vu/app/index.html");
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setGeolocationEnabled(true);
        myWebView.setWebViewClient(new CustomWebViewClient());
    }
    private class CustomWebViewClient extends WebViewClient {
        @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        }   
    WebView myWebView;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

但它不起作用,当我返回应用程序崩溃并要求我关闭它时。不是我做错了什么,因为我看到的所有代码都是如此 Webview 和功能。为什么我的不工作?

4

3 回答 3

3

您有一个WebView myWebView;从未分配过的声明。要解决此问题,您可以更改:

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

myWebView = (WebView) findViewById(R.id.wvBrowser);
于 2013-04-04T12:23:04.823 回答
1
package com.android.m2s;

import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView) findViewById(R.id.wvBrowser);
        myWebView.loadUrl("http://www.message2space.es.vu/app/index.html");
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setGeolocationEnabled(true);
        myWebView.setWebViewClient(new CustomWebViewClient());
    }
    private class CustomWebViewClient extends WebViewClient {
        @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        }   
    WebView myWebView;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

这将起作用

于 2013-04-04T12:35:13.723 回答
0

你为什么不直接使用:

YourActivity.this.onBackPressed();
于 2013-04-04T12:21:39.100 回答