Transparent WebView on Android Devices

I’m trying to re-write a java android app into Xamarin.Android, however I have come across an issue with the background transparency of the WebView that I use to display the contents of each screen.

This code works correctly on the java version (Black text on a green background), but in the C# version, the WebView’s background is black (black rectangle on the green background).

Java Code:

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout layout = new LinearLayout(getApplicationContext());
        layout.setBackgroundColor(Color.GREEN);
        WebView webView = new WebView(getApplicationContext());
        layout.addView(webView);
        setContentView(layout);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.setBackgroundColor(Color.TRANSPARENT);
        String html = "<html><body style='background-color: transparent;'>Some text...</body></html>";
        webView.loadData(html, "text/html", "UTF-8");
    }

C# Code:

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        var layout = new LinearLayout(ApplicationContext);
        layout.SetBackgroundColor(Color.Green);
        var webView = new WebView(ApplicationContext);
        layout.AddView(webView);
        SetContentView(layout);

        webView.Settings.JavaScriptEnabled = true;
        webView.SetBackgroundColor(Android.Graphics.Color.Transparent);
        string html = "<html><body style='background-color: transparent;'>Some text...</body></html>";
        webView.LoadData(html, "text/html", "UTF-8");
    }

There is also a ‘Android.Resource.Color.Transparent’, but don’t use this one as values returned from the Android.Resource namespace are resource ids, not colours.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s