- 1、不要在布局中直接初始化 webview,而是在需要的时候在 Activity 中动态创建 webview ,并且在创建 webview 时使用 Application 的上下文。
代码示例如下:
LinearLayout.LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MatchParent,ViewGroup.LayoutParams.MatchParent);
WebView wv = new WebView(getApplicationContext());
wv.setLayoutParams(lp);
linearyLayout.addView(wv);
- 2、在销毁 webview 的时候,先让 webview 加载空内容,清空历史,然后移除 webview ,然后再销毁webview。
具体代码如下:
@Override
protected void onDestroy(){
//先加载空内容
if(wv!=null){
//先加载空内容
wv.loadDataWithBaseUrl(null,"","text/html","utf-8",null);
//清空历史
wv.clearHistory()
//从布局中移除
((ViewGroup)wv.getParent()).removeView(wv);
//然后销毁
wv.destroy();
//然后置为空
wv=null;
}
}
网友评论