Android WebView在单击“返回”时停止

时间:2015-05-21 11:00:18

标签: android webview

我的webview模块无效。每当我尝试从任何网页导航回来时,应用程序崩溃都会出现以下错误

 "Unfortunately the app has stopped".

任何人都可以解释一下是什么原因?

public class MainActivity extends ActionBarActivity {
WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView mainWebView = (WebView) findViewById(R.id.mainWebView);

    WebSettings webSettings = mainWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mainWebView.setWebViewClient(new MyCustomWebViewClient());
    mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    mainWebView.loadUrl("http://nahdaschools.com/v4/index.php/apps");
}

private class MyCustomWebViewClient extends WebViewClient
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {
        view.loadUrl(url);
        return true;
    }

}

@Override
public void onBackPressed() {
    if (myWebView.copyBackForwardList().getCurrentIndex() > 0) {
        myWebView.goBack();
    }
    else {
        // Your exit alert code, or alternatively line below to finish
        super.onBackPressed(); // finishes activity
    }
}}

2 个答案:

答案 0 :(得分:0)

有了这个,你就可以参加上一次的活动了。

     @Override
      public void onBackPressed() {

        super.onBackPressed(); 
           moveTaskToBack(false);// finishes activity
         }   

 }}

答案 1 :(得分:0)

   @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

     if(event.getAction() == KeyEvent.ACTION_DOWN){
         switch(keyCode)
         {
         case KeyEvent.KEYCODE_BACK:
         if(myWebView.canGoBack()){
              myWebView.goBack();
        }
       else{
             finish();
          }
            return true;
        }

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