Issue
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
.
Solution
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)
Answered By - Fat Monk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.