以下是使用WebView过程中的部分场景和解决方案
- 支持Copy功能 (参考另一篇: http://ihavegotyou.iteye.com/blog/1395721 )
public static synchronized void emulateShiftHeld(WebView view) { try { KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0); shiftPressEvent.dispatch(view); } catch (Exception e) { Log.e(TAG, "Exception in emulateShiftHeld()", e); } } public static synchronized void selectAndCopyText(WebView v) { try { Method m = WebView.class.getMethod("emulateShiftHeld", Boolean.TYPE); m.invoke(v, false); } catch (Exception e) { // fallback emulateShiftHeld(v); }finally{ } }
- 如果WebView是放在TabHost中的Activity, 而且WebView中包含html的select,会在点击其中的Item时候崩溃,异常信息如下: android.view.WindowManager$BadTokenException: Unable to add window
token android.app.LocalActivityManager$LocalActivityRecord@44ed8338 is not valid; is your activity running?解放方法:用代码生成WebView( new WebView(this.getParent() == null ? this : this.getParent())),而不是直接用Xml layout. - 重写WebView中的href(在新的窗口打开或在当前页面打开)
_webView.setWebViewClient(new WebViewClient(){ public boolean shouldOverrideUrlLoading(WebView view, String url) { TDStockLog.d(TAG, url); if(url.indexOf("&id=")!=-1){ forwardMessageContentActivity(url); }else{ _webView.loadUrl(url); } return true; } });
- 显示本地Html
public void setWebContextDefault(){ if(_webView!=null){ String summary="<html><head></head><body>"+this.getString(R.string.service_not_available)+"</body></html>"; TDStockLog.d(TAG, "content=" + summary); //_webView.getSettings().setBuiltInZoomControls(true); //_webView.getSettings().setJavaScriptEnabled(true); _webView.loadDataWithBaseURL(null, summary, "text/html","utf-8", null); } }
- 从低版本开始支持放大缩小
webSettings.setBuiltInZoomControls(true);