1

I'm targeting SDK version 27 and currently testing on Oreo (physical device) and API19 (emulator) and want to set the background of a WebView to transparent.

There are a lot of answers for earlier API/SDK versions, but nothing seems to be working for me on these versions.

Specifically I am loading a URL that returns an image only into my WebView. The WebView is slightly wider than the image (as the image size may vary).

I can always see a black background around the image (I have confirmed that this is NOT part of the image)

In the onPageFinished method of the WebViewClient attached to my WebView I am trying all of the following:

wv.setBackgroundColor(Color.TRANSPARENT)
wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null)
wv.setBackgroundResource(android.R.color.transparent)

I have also set the layer type to LAYER_TYPE_HARDWARE.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Fat Monk
  • 2,077
  • 1
  • 26
  • 59

2 Answers2

0

This will make the webview activity transparent.

<style name="AppTheme.Transparent" parent="AppTheme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
</style>

Add this as the theme of the webview activity in your manifest

<activity android:name=".WebViewActivity" android:theme="@style/Theme.Transparent">
NirmalCode
  • 2,140
  • 1
  • 14
  • 19
0

It turns out that the above code WAS in fact making the WebView transparent and that the black surround that I was seeing was actually the default background of the pseudo-body of the rendered page when the page contains only an image. (This answer gave me the clue!)

The trick, therefore was to create an HTML page on the fly with a transparent body and include the image in that page rather than just loading the image into the WebView directly.

So, using:

wv.setBackgroundColor(Color.TRANSPARENT)
wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null)

in the onPageFinished method AND using

String myHTML = "<html><body style=\"background: transparent; margin:0; padding:0;\"><img src=\"" +
                myImgURL + "\"></body></html>";
wv.loadData(myHTML, "text/html", "UTF-8");

Has achieved the desired effect of displaying the image in the WebView as though it were directly on the canvas.

(Note that I have tried with and without the setLayerType line and it still works in Oreo - it may or may not be needed in other versions)

Fat Monk
  • 2,077
  • 1
  • 26
  • 59