Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView Internationalization

What is the best way to handle internationalization/localization in an Android WebView. Ideally, I would like to access all the string resources in:

res/values/strings.xml res/values-de/strings.xml ...

Has anybody done this in an efficient way?

Android Localization information: http://developer.android.com/guide/topics/resources/localization.html

Best, -- Thomas Amsler

like image 248
tamsler Avatar asked Jul 07 '11 20:07

tamsler


1 Answers

To load some localized data in a webview, I created a string containing a localized URL, and used that to load an HTML file. So for example a string:

<string name="url_to_load">file:///android_asset/localized_ru.html</string>

to reference a file localized_ru.html in the /assets directory, and then in the activity:

webView.loadUrl(getString(R.string.url_to_load));

I used this indirect via a string since assets/ directory is not localized, and loading a resource using a URL didn't work for me.


If you really want to be able to load all string resources from your webview, you can create a JavaScript-interface and a simple helper class:

class Localizer {
    private Resources res;

    public Localizer(Resources res) {
        this.res = res;
    }
    public String get(String key) {
        int id = res.getIdentifier(key, "string", "org.example.app");
        return res.getString(id);
    }
}

then pass that to the webview in your activity:

webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Localizer(getResources()), "localizer");
like image 198
beetstra Avatar answered Sep 19 '22 11:09

beetstra