webview后退按钮错误

时间:2015-11-18 12:44:37

标签: android javascript-events webview android-webview

在我的webview应用程序中,如果按下后退按钮,我会收到错误很遗憾应用程序已停止

我尝试过2种不同的后退按钮方式。我错过了什么吗?

P.s第一个应用程序所以请耐心等待我

  package au.com.industryresponsetraining.mdt;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private WebView mwebview;

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

        String "http://www.google.com";
        WebView mwebview = (WebView) this.findViewById(R.id.webView);
        mwebview.getSettings().setJavaScriptEnabled(true);
        mwebview.loadUrl(url);
        mwebview.setWebViewClient(new WebViewClient());
    }

    private class MyWebviewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("http://www.google.com")) {
                return false;
            } else {
                //here open external links in external browser or app
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }

        }
    }
//back button function thats not working
    @Override
    public void onBackPressed() {
        if (mwebview.canGoBack()) {
            mwebview.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

你的onCreate方法应该是

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

    String "http://www.google.com";
    mwebview = (WebView) this.findViewById(R.id.webView);

}

而不是

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

    String "http://www.google.com";
    WebView mwebview = (WebView) this.findViewById(R.id.webView);

}

答案 1 :(得分:1)

试试这个:

@Override
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);
}