是否可以在 Android Studio 中创建可翻译的任意 XML 资源?

Is it possible to create translateable arbitrary XML resources in Android Studio?

我想创建一个应用程序来询问用户问题,对答案进行评分并可能对他们做出反应并提出后续问题。为此,我想到了 res/xml/questions.xml 中的 XML 之类的东西:

<?xml version="1.0" encoding="utf-8"?>
<questions>
    <question id="000" category="2">
        <text>Yes or no?</text>
        <answers>
            <choice id="0" score="+5">Yes</choice>
            <choice id="1" score="-5">No</choice>
        </answers>
    </question>
    <question id="010" category="1">
        <parent id="000" choice="0"/>
        <text>Whats my question?</text>
        <answers>
            <choice id="0" score="-5">Shut up.</choice>
            <choice id="1" score="0">I don't care.</choice>
            <choice id="2" score="+5">I like your attitude!</choice>
        </answers>
    </question>
</questions>

我想支持多国语言。如何在不在不同的 XML 中重新定义相同逻辑的情况下翻译 <text><choice> 的内容? (或者我应该完全放弃 XML 方法吗?)

这里有一些选项:

选项 #1:res/xml/questions.xml 和 XML 的其他变体用于不同的语言(例如,res/xml-es/questions.xmlres/xml-de/questions.xmlres/xml-zh/questions.xml

选项 #2:在您拥有英文字符串的地方,改为拥有映射到字符串资源的值。所以,res/xml/questions.xml 可能看起来像:

<?xml version="1.0" encoding="utf-8"?>
<questions>
    <question id="000" category="2">
        <text>question_000</text>
        <answers>
            <choice id="0" score="+5">question_000_choice_0</choice>
            <choice id="1" score="-5">question_000_choice_1</choice>
        </answers>
    </question>
    <question id="010" category="1">
        <parent id="000" choice="0"/>
        <text>question_010</text>
        <answers>
            <choice id="0" score="-5">question_010_choice_0</choice>
            <choice id="1" score="0">question_010_choice_1</choice>
            <choice id="2" score="+5">question_010_choice_2</choice>
        </answers>
    </question>
</questions>

那么您将拥有 question_000question_000_choice_0 等的字符串资源。当您解析 XML 时,您然后在 Resources 对象上使用 getIdentifier() 来查找与 question_000_choice_0.

等内容对应的字符串资源 ID

选项 #3:让 XML 简单描述一下基础知识:

<?xml version="1.0" encoding="utf-8"?>
<questions>
    <question id="000" category="2">
        <answers>
            <choice id="0" score="+5" />
            <choice id="1" score="-5" />
        </answers>
    </question>
    <question id="010" category="1">
        <parent id="000" choice="0"/>
        <answers>
            <choice id="0" score="-5" />
            <choice id="1" score="0" />
            <choice id="2" score="+5" />
        </answers>
    </question>
</questions>

您仍然会有 question_000question_000_choice_0 等的字符串资源。但是,您不必在 XML 中使用这些名称,而只需从问题和选择 ID 中生成它们。