2

How to set transparent color in android webview?

<div style="background-color: black" >test</div>

How can I make black color to be transparent for the whole page (like chromakey)?

VaMpir
  • 61
  • 2
  • 6

4 Answers4

8

Had the same problem with the WebView, as it behaved randomly across different OS versions. Finnlay I fixed it with this code this after the loadDataWithBaseURL() call:

if (Build.VERSION.SDK_INT >= 11) {
    webView.setBackgroundColor(0x01000000);
} else {
    webView.setBackgroundColor(0x00000000);
}

I figure this will give the device something to draw, so various caching mechanisms will not kick in. But the result is practically the same as with total transparency, as it is undetectable by average human eye.

No performance penalties noticed as well.

Tested on several devices ranging from 2.2 to 4.2.

Cheers

Sabo
  • 1,635
  • 1
  • 19
  • 24
2

try this

(YourWebview).setBackgroundColor(0x00000000);
John Jared
  • 790
  • 3
  • 16
  • 40
  • I tryed, but it only sets transparent background for webview, not for html elements inside it. As I wrote in the first message if I create div-element with black background and text inside it I get transparent webview but text is still on black background. – VaMpir Aug 21 '12 at 06:24
1

I've found the solution. I've reimplemented OnDraw method of WebView

@Override
    protected void onDraw(android.graphics.Canvas canvas) {

    super.onDraw(canvas);

    Paint p = new Paint();

    p.setARGB(255, 0, 0, 0);
    int removeColor = p.getColor(); 

    p.setAlpha(1); // if Alpha is 0 it doesn't work. I don't know why
    p.setXfermode(new AvoidXfermode(removeColor, 0, AvoidXfermode.Mode.TARGET));

    canvas.drawPaint(p);
}
VaMpir
  • 61
  • 2
  • 6
  • Just my two pence; transparency in WebViews pre Android 4.0.3+ have logged bugs. There are a number of threads on SO regarding this point. – BrantApps Aug 23 '12 at 21:37
0

you can use this

webView.setBackgroundColor(0);
ghader
  • 369
  • 3
  • 9