我正在编写一个带有 webview 的应用程序,其中我有超链接。当我转到超链接时,我无法用我的后退键返回我的主站点。这是我的 webview 代码:
public class WebViewActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
/*------------enable javascript--------------- */
WebSettings webSettings = webView.getSettings();
webView.getSettings().setJavaScriptEnabled(true);
/*-------------------------------------------- */
/*------------enable Zoom--------------- */
webView.getSettings().setBuiltInZoomControls(true);
/*-------------------------------------------- */
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
/*------------size of the webpage in webview--------------- */
webView.setPadding(0, 0, 0, 0);
webView.setInitialScale(40); // 0 - 100 where 100 is full scal
/*-------------------------------------------- */
/*------------call url ------------------------ */
webView.loadUrl("http://www.example.gr");
webView.setWebViewClient(new MyWebViewClient() );
/*-------------------------------------------- */
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webView.loadUrl(url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if((keyCode == KeyEvent.KEYCODE_BACK) && !( webView.canGoBack() ) ){
webView.loadUrl("http://www.example.gr");
return false;
}
else if (webView != null && (keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack() ) {
webView.goBack();
return false;
}
return super.onKeyDown(keyCode, event);
}
}