我的Webview应用程序运行良好,没有任何错误,但是当我按下“返回”按钮时,它崩溃了

时间:2018-07-14 13:56:52

标签: java android webview

我正在android studio中开发Webview应用,但遇到了一些问题。我的应用程序运行良好,没有任何错误即可编译并运行。但是当我按下返回按钮时,它崩溃了。请帮我,因为我必须将它汇总到我的大学中

这是我正在使用的我的代码:

public class MainActivity extends AppCompatActivity{
private ProgressBar progressBar;
private Toolbar toolbar;
private WebView webView;

@SuppressLint("SetJavaScriptEnabled")
@Override    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    progressBar.setVisibility(View.GONE);
    WebView webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClientDemo());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    webView.getSettings().setAppCacheEnabled(true);
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setSavePassword(true);
    webView.getSettings().setSaveFormData(true);
    webView.getSettings().setLoadsImagesAutomatically(true);
    webView.loadUrl("https://google.in/");


}

private class WebViewClientDemo extends WebViewClient {

    @Override        public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
    @Override        public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
        progressBar.setProgress(100);
    }
    @Override        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setProgress(0);

    }

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

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

}

1 个答案:

答案 0 :(得分:2)

只需更改此行:

salesorderdetail

对此:

WebView webView = (WebView) findViewById(R.id.webView);

就这样,尽情享受:)