Dav*_*e W 4 c# localization cross-platform xamarin.android xamarin
使用Xamarin Android,可以为多语言应用创建本地化字符串,如Android文档中所示:
但是,我的模型中有各种try/catch块,它们将错误消息作为字符串发回.理想情况下,我想保持我的解决方案的模型和控制器部分完全跨平台,但我看不到有效地本地化消息的任何方法,而无需将非常特定于平台的Android上下文传递给模型.
有没有人有关于如何实现这一目标的想法?
我正在使用.net资源文件而不是Android 资源文件.它们让我可以从代码访问字符串,无论它在哪里.
我不能自动做的唯一事情就是从布局中引用这些字符串.为了解决这个问题,我编写了一个快速实用程序,它解析resx文件并创建一个具有相同值的Android资源文件.它在Android项目构建之前运行,因此所有字符串都在适当的位置.
免责声明:我还没有用多种语言对此进行测试.
这是该实用程序的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace StringThing
{
class Program
{
static void Main(string[] args)
{
string sourceFile = args[0];
string targetFile = args[1];
Dictionary<string, string> strings = LoadDotNetStrings(sourceFile);
WriteToTarget(targetFile, strings);
}
static Dictionary<string, string> LoadDotNetStrings(string file)
{
var result = new Dictionary<string, string>();
XmlDocument doc = new XmlDocument();
doc.Load(file);
XmlNodeList nodes = doc.SelectNodes("//data");
foreach (XmlNode node in nodes)
{
string name = node.Attributes["name"].Value;
string value = node.ChildNodes[1].InnerText;
result.Add(name, value);
}
return result;
}
static void WriteToTarget(string targetFile, Dictionary<string, string> strings)
{
StringBuilder bob = new StringBuilder();
bob.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
bob.AppendLine("<resources>");
foreach (string key in strings.Keys)
{
bob.Append(" ");
bob.AppendLine(string.Format("<string name=\"{0}\">{1}</string>", key, strings[key]));
}
bob.AppendLine("</resources>");
System.IO.File.WriteAllText(targetFile, bob.ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5150 次 |
| 最近记录: |