Search code examples
androidwebviewpng

Transparent PNG in WebView on Android


I have some PNG files with transparent backgrounds that I want to put in a web page to view in an Android WebView. The WebView is set to have an image as a background. I've noticed the transparency works in, say, Google chrome, even on the cell phone itself, but the images come up with a white background in my WebView. Here is the markup for the page:

<div id="image_container">
    <img src="teststicker1.png" style="background-color:transparent;"  />
    <img src="teststicker2.png" style="background-color:transparent;" />
    <img src="teststicker3.png" style="background-color:transparent;"/>
    <img src="teststicker4.png" style="background-color:transparent;"/>
</div>

How do I achieve transparency so the background falls through to the background of the WebView instead of being white? I've searched this site and found similar questions but none quite the same, and none of the answers there worked.

The code for initializing the WebView is

myWebView.loadUrl(getActivity().getResources().getString(R.string.site_url)+getActivity().getResources().getString(R.string.image_picker_html));
myWebView.setBackgroundResource(R.drawable.image_gallery_2_2);              
myWebView.setBackgroundColor(Color.TRANSPARENT);

enter image description here


Solution

  • After loading the content on your webView set the background color for the webview to transparent using this:

    yourWebView.setBackgroundColor(Color.TRANSPARENT);
    

    Clear cache everytime after creating web view in your code to avoid loading of cached pages. (point pulled from my comment below)

    yourWebView.clearCache(true);