【问题标题】:Best practice for mapping variables with translations使用翻译映射变量的最佳实践
【发布时间】:2012-10-30 08:33:09
【问题描述】:

我有一张表,里面有很多行需要翻译。大多数值都是整数,因此不需要翻译这些值。

但是,我的数据来自 JSON 结构,其中数据以键值对的形式正常存储。例如:

{
  "age":24,
  "hair-color":"black",
  "weight":42,
  "height":123,
  // ...
}

到目前为止,我有一个如下所示的 strings.xml:

<resources>
  <string name="meta_age">Alter</string>
  <string name="meta_hair_color">Haarfarbe</string>
  <string name="meta_weight">Gewicht</string>
  <string name="meta_height">Körpergröße</string>
  <!-- ... -->
</resources>

这些数据在带有自定义 ArrayAdapter 的列表视图中可视化。这很好用,但是我不确定将键值对与其翻译映射的最佳方法是什么。

我现在有这段代码:

public static final int[] fields = new int[] {R.string.meta_age, R.string.meta_hair_color, R.string.meta_weight, R.string.meta_height, /* ... */;

为了构建 UI,字符串需要映射到 keys 到目前为止,这是通过这个凌乱的代码完成的:

List<Integer> fieldIndex = new ArrayList<Integer>(fields.length);
for(int i : fields) {
    fieldIndex.add(i);
}
translation = new HashMap<String, Integer>();
translation.put("age", fieldIndex.indexOf(R.string.meta_age));
translation.put("hair-color", fieldIndex.indexOf(R.string.meta_hair_color));
translation.put("weight", fieldIndex.indexOf(R.string.meta_weight));
translation.put("height", fieldIndex.indexOf(R.string.meta_height));

下一步是我现在知道 json 字段的目标索引,并将它们与字符串 id 的字段列表放在一起。但我认为这段代码的性能不是很好。我怎样才能写得更好?

【问题讨论】:

    标签: android performance optimization internationalization


    【解决方案1】:

    听起来确实有点复杂。为什么不只是以一种键/翻译的方式拥有所有可能的翻译的字典。
    大多数翻译框架也是这样工作的。

    【讨论】:

    • 那么带有 R.string 的东西通常适用于 Android。我只是不确定我的映射是否有意义......
    • 如果您在我们的翻译资源文件中拥有一个可以一次性映射到您的翻译的密钥不是更容易吗?例如。而不是使用 meta_hair_color,而是使用 json 中的 meta_hair-color?然后你可以直接根据他们的名字得到翻译字符串。没有?
    • 翻译变量中不允许使用减号,并且 json 来自 external API。该字段数组的另一个原因是我不想使用 JSON 字符串的顺序。
    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 2023-03-16
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多