如何使它在android webview中的后退按钮工作?

时间:2013-04-04 12:19:11

标签: android eclipse webview back

我有这段代码:

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和功能。为什么我的不工作?

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分: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);
    }
}

这将有效

答案 2 :(得分:0)

为什么不使用:

YourActivity.this.onBackPressed();