62

I have a WebView in my app with wrap_content width and height

Before I use webview.loadData, the width and height of the it was 0, after I load a page (or I use webview.loadData) , it'll display a web page.

My question is , how can I clear the webview to recover it back to the original state, just as before it loadData?

Lii
  • 11,553
  • 8
  • 64
  • 88
peterlawn
  • 2,371
  • 6
  • 25
  • 44
  • possible duplication, http://stackoverflow.com/questions/8939530/how-do-i-clear-previous-webviews-content-before-loading-the-next-webview/25452749#25452749 – E_X Aug 22 '14 at 17:46

6 Answers6

88

I found this answer, pretty helpful: How do I clear a WebView's content before loading a page?

It is for Cocoa, but basically just call:

webView.loadUrl("about:blank")
Lii
  • 11,553
  • 8
  • 64
  • 88
Grantland Chew
  • 2,620
  • 26
  • 26
  • 3
    But, by using such approach, this seems to have behaviour, you need to press the back button twice (I think the extra is for blank page), in order to navigate webview previous content. There's a discussion http://stackoverflow.com/a/8939753/72437 but I don't find it works for me. – Cheok Yan Cheng Aug 05 '15 at 02:28
  • @CheokYanCheng i'm using webView.clearView(). I know, it's deprecated, but this only acceptable solution for me now – Dehimb Mar 15 '16 at 17:42
51

The only complete solution is to check for SDK version.

if (Build.VERSION.SDK_INT < 18) {
   webView.clearView();
} else {
   webView.loadUrl("about:blank");
}
sandalone
  • 41,141
  • 63
  • 222
  • 338
  • 1
    this solution helped me byt with `webView.destroyDrawingCache();` now works fine on all versions. Without destroing drawing cache were old content blinks on 4.4.+ androids – Taras Mazepa Oct 02 '14 at 14:58
  • 3
    WebView.clearView() is deprecated, use loadUrl('about:blank") instead Source : http://developer.android.com/reference/android/webkit/WebView.html#clearView%28%29 – Hugo Gresse Dec 02 '14 at 09:58
  • 2
    As @HugoGresse suggests, use `webView.loadUrl("about:blank")` for all SDK versions. `webView.clearView()` often isn't working correctly if Javascript is running, even in SDK versions < 18. – Oliver Hausler Apr 29 '15 at 22:44
10

use following statement before loadData:

view.loadUrl("javascript:document.open();document.close();");
partlov
  • 13,789
  • 6
  • 63
  • 82
5

WebView.clearView();

This will clear the view from the webview.

Sudheesh VS
  • 257
  • 3
  • 4
  • 5
    Warning : Deprecated. Use WebView.loadUrl("about:blank") to reliably reset the view state and release page resources (including any running JavaScript). – vipsy Mar 05 '14 at 08:30
1

I used the clearView() method, however I'm now having issues that when I loadData() right after it, it doesn't seem to load the data.

Adam
  • 1,076
  • 1
  • 11
  • 24
0

What about loadUrl("about:blank"), and then clearHistory()?

HelloWorld
  • 3,381
  • 5
  • 32
  • 58