【问题标题】:How to automatically access strings.xml? (Android)如何自动访问strings.xml? (安卓)
【发布时间】:2013-11-14 04:34:01
【问题描述】:

我在strings.xml中有一堆字符串, 字符串的所有 ID/名称都有一个模式 (e0,e1,e2,e3,e4...) 我想显示我拥有的 23 个字符串之一 用户选择什么号码。例如,如果用户选择 数字 6,而不是我想要显示字符串“e6”。 如何在不使用超长 switch 语句的情况下做到这一点?

我正在使用 IntelliJ Idea

感谢您的帮助,您的所有答案都有效且有用。

【问题讨论】:

    标签: java android xml string intellij-idea


    【解决方案1】:

    你可以使用字符串数组

    http://developer.android.com/guide/topics/resources/string-resource.html#StringArray

    示例:

    XML 文件保存在 res/values/strings.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string-array name="planets_array">
            <item>Mercury</item>
            <item>Venus</item>
            <item>Earth</item>
            <item>Mars</item>
        </string-array>
    </resources>
    

    此应用程序代码检索字符串数组:

    Resources res = getResources();
    String[] planets = res.getStringArray(R.array.planets_array);
    

    【讨论】:

      【解决方案2】:

      离开迈克尔的例子,我会做这样的事情:

      Int num; //the number the user chooses
      
      TextView tv = (TextView) findViewById(R.id.textviewID);
      
      tv.setText(planets[num - 1]); //arrays start at zero so you would have to subtract one to get the right string. And also so you dont reference a nonexistent variable in the array.
      

      【讨论】:

      • 谢谢你提醒我把'num'减1,否则我会忘记自己
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多