Android – Transparent WebView not working on Android v4.0

androidandroid-webview

Some background to this question is here. It relates to working around a known bug in Android where the WebView background needs to be transparent.
Android WebView style background-color:transparent ignored on android 2.2

It involves a WebView, hosting an HTML document with a transparent background, so the WebView is transparent and the HTML document can be overlaid onto other views.

Adding the following method to the WebView subclass and calling it from the constructor works for me on Android v2, v3, and v4, EXCEPT when the pixel height of the WebView is larger than the screen height in pixels (e.g. the WebView is in a ScrollView, so longer than the screen).

protected void setBackgroundToTransparent() {
    this.setBackgroundColor(Color.TRANSPARENT);
    this.setBackgroundDrawable(null);
    if (Build.VERSION.SDK_INT >= 11) // Android v3.0+
        try {
         Method method = View.class.getMethod("setLayerType", int.class,  Paint.class);
         method.invoke(this, 1, new Paint());  // 1 = LAYER_TYPE_SOFTWARE (API11)
        } catch (Exception e) {}
}

Best Answer

I've encountered the same problem and what I found is that this is a bug in some versions of Android regarding hardware acceleration. Spiri's answer above works, but I needed my WebView to be hardware accelerated because it needs to play videos. What I found works well, is the following:

Instead of using

mWebView.setBackgroundColor(Color.TRANSPARENT);

What I used was:

mWebView.setBackgroundColor(Color.argb(1, 255, 255, 255));

This worked on all the Android devices where I was previously having this issue.