Friday, September 14, 2012

Mono Android html asset localization

While on the subject of localization, I have created some activities of my app as static web-pages. These pages can be stored as an Android asset and loaded at runtime. This provides an easy option for creating complex layouts without the hassle of doing it all in that horribly tortuous axml format.

A static web page can be saved in the Assets directory and reconstituted using Assets.Open(...). This can present problems however because assets are not localizable in the same way that strings are. Rather than duplicating the HTML in the strings.xml files and localizing each on individually, I created a barebones file with replaceable chunks that are themselves localized.

An HTML file could contain:

<html>
<head>
<title>{TITLETEXT}</title>

here be scripts and good stuff...

</head>
<body>

{BODYTEXT1}

Here be boilerplate...

{BODYTEXT2}

</body>
</html>

Obviously the html would need to be complex enough that you wouldn't want or be able to duplicate the whole thing. A good excuse is that maintaining the same page info in one place is better than maintaining it in every localized resource file.

So, to load my HTML in I use:


            var wv = (WebView)FindViewById(Resource.Id.registerwebview);
            var sr = new StreamReader(Assets.Open("reg1.htm"));
            string barebones = sr.ReadToEnd();
            barebones = barebones.Replace("{TITLETEXT}", Resources.GetString(Resource.String.registertitle));
            barebones = barebones.Replace("{HEADERTEXT}", Resources.GetString(Resource.String.registertitle));
            barebones = barebones.Replace("{BODYTEXT}", Resources.GetString(Resource.String.registerblurb));
            wv.LoadDataWithBaseURL("file:///android_asset/",barebones, "text/html", "utf-8", "");


Et voila.. a localized HTML page that looks great, contains images also pulled in from assets, scripts, links and JQuery interactions with the backend...


No comments: