是否可以在Android Studio中创建可翻译的任意XML资源? [英] Is it possible to create translateable arbitrary XML resources in Android Studio?

查看:56
本文介绍了是否可以在Android Studio中创建可翻译的任意XML资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个应用程序,它向用户提问,给答案打分,并可能对他们提出后续问题做出反应。为此,我在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>

我希望支持多种语言。如何翻译<text><choice>的内容,而不需要在不同的XML中重新定义相同的逻辑?(或者我应该完全放弃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等的字符串资源。但是,您只需从问题ID和选择ID生成这些名称,而不是将这些名称放在XML中。

这篇关于是否可以在Android Studio中创建可翻译的任意XML资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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