Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent WebView not working on Android v4.0

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) {}
}
like image 494
Ollie C Avatar asked Feb 14 '12 18:02

Ollie C


People also ask

What is translucent in Android?

One of the new features in KitKat is the Translucent UI, where you have the ability to sit behind status and navigation bars, meaning you can have the subtle change shown above (left side is normal, right side is the translucent version).

How do I change the color of the opacity on my Android?

setAlpha(51); Here you can set the opacity between 0 (fully transparent) to 255 (completely opaque). The 51 is exactly the 20% you want.


1 Answers

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.

like image 69
Alexandru Dragutu Avatar answered Sep 20 '22 15:09

Alexandru Dragutu