Android WebView国际化 [英] Android WebView Internationalization

查看:204
本文介绍了Android WebView国际化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android WebView中处理国际化/本地化的最佳方法是什么.理想情况下,我想访问以下位置的所有字符串资源:

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 ...

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

有人有效地做到了吗?

Android本地化信息: http://developer.android.com/guide/topics/resources/localization.html

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

最好, -托马斯·阿姆斯勒(Thomas Amsler)

Best, -- Thomas Amsler

推荐答案

要在Webview中加载某些本地化数据,我创建了一个包含本地化URL的字符串,并使用该字符串来加载HTML文件. 例如一个字符串:

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>

引用文件localized_ru.html/assets目录中,然后在活动中:

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

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

由于未对assets/目录进行本地化,因此我通过字符串间接使用了该内容,并且使用URL加载资源对我而言不起作用.

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.

如果您确实希望能够从Web视图中加载所有字符串资源,则可以创建一个JavaScript接口和一个简单的帮助程序类:

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");

这篇关于Android WebView国际化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆