Android WebView Internationalization
What is the best way to handle internationalization/local开发者_高级运维ization 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
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");
You can send localized string resources data to your WebView
. Look into WebView.postUrl()
精彩评论