我正在开发一个 Android
应用程序,并希望将其翻译为波斯语。
项目中的所有 String
值都保存到资源 XML
文件中。
一些 String
值用于布局文件,一些用于类 (R.String)。在 Android
中使用波斯语文本时,必须重新调整其形状才能正确显示。
我想 reshape 所有资源 String
值,而不为每个 String
值调用 reshape 方法。
谁能解释一下我该怎么做?
一些想法:
覆盖 String 类
重写 getResource 类
最佳答案
Android
已经提供了拥有多语言应用程序的功能 ( well documented )。与其替换文本并为每种语言提供多个版本的应用程序,不如使用框架功能。在这种情况下,应用程序会根据设备区域设置从您提供的可用语言中选择合适的语言。
所以基本上您可以从创建所需的目录结构开始(上面的链接):
MyProject/
res/
values/
strings.xml
values-fa/
strings.xml
然后将String
值填充到文件中,例如:
英语(默认区域设置),/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">My Application</string>
<string name="hello_world">Hello World!</string>
</resources>
波斯语,/values-fa/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">...</string>
<string name="hello_world">...</string>
</resources>
(引用并改编自上面的链接)
reshape farsi 的解决方案语言
reshape 函数必须用于每个波斯语 String
值,因此在 XML
布局中设置字符串是不可能的(AFAIK),因此以下建议假设,所有String
值以编程方式设置。
使用全局静态包装函数#1
public static final String getLocalizedString(int resId) {
if(Locale.getDefault().toString().equals("fa_IR")) {
return PersianReshape.reshape(getResources().getString(resId));
}else{
return getResources().getString(resId);
}
您现在可以使用此函数来加载String
(您必须更改每次出现的情况)或者覆盖例如getRessource 方法。我个人更喜欢使用静态函数而不是重写,因为加载 String
以外的其他类型的资源可能会出现其他问题、副作用等。
为每个使用的 ui 小部件创建一个重写 setText() 的自定义类 #2
另一种可能性是创建自定义 ui 小部件,在显示时调用 PersianReshape.reshape()
。例如。对于 EditText
:
class CustomTextField extends EditText {
@Override
public void setText(String text) {
super.setText(PersianReshape.reshape(text));
}
}
[...]
CustomTextField myTextBox = new CustomTextField();
myTextBox.setText("....");
关于java - android reshape 所有资源文件字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23213968/