Please help Ukrainian armed forces! Official Fundraising

Android WebView transparent background for Android 2.3 and up

1 1 1 1 1 Android WebView transparent background for Android 2.3 and up5.00Rating 4.96 (666 Votes)

Many people face an issue with Android's WebView and transparent background. The problem is that if you need to make transparent background for the WebView, it is not easy to do at the first sight. If you try to use property android:background="@android:color/transparent", you will discover that it just don't work as expected. The background is still opaque. Using background color set explicitly as #ff000000 constant sometimes work and sometimes not. 

The most popular recommendation on the Web seems to be setting android:hardwareAccelerated="false" and also calling webView.setBackgroundColor(0x00000000). This code seems to work fine on Android 4.x, but you will get completely black WebView control on Android 2.2/2.3:

black webview

Seems to be that WebView works somehow different on Android 2.x and later platforms. But how do we make it transparent on both platforms?


Of course, if you are not targeting Android 2.2 and 2.3, this won't be an issue for you, but Androind 2.x are still very popular nowadays and own approximately 15% market share in total.

Do you need to develop custom Android application? Hire people who know the stuff! Our professional Android developers can help you!

The most versatile solution I've found is this code:

webView.setBackgroundColor(0x00000000);
if (Build.VERSION.SDK_INT >= 11) webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

this.wv.setWebViewClient(new WebViewClient()
{
    @Override
    public void onPageFinished(WebView view, String url)
    {
        view.setBackgroundColor(0x00000000);
        if (Build.VERSION.SDK_INT >= 11) view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    }
});

Put this code in an onCreate method in your activity just after the code:

webView = (WebView) findViewById(R.id.webView);

Of course, variable name for WebView and ID may differ in your code, so you need to adjust them to match your declarations.

Also you need to remove android:hardwareAccelerated="false" and android:layerType = "software" from your manifests ans layouts.

This solution works great for me. This allows to build an applications with transparent WebView that behaves correct both on Android 2.2, 2.3 and 4.x.

Source: Stackoverflow.com

You have no rights to post comments

Thursday the 21st.