【问题标题】:Android - String Array with switch statementAndroid - 带有 switch 语句的字符串数组
【发布时间】:2012-10-03 09:32:20
【问题描述】:

我正在寻找有关如何实现从字符串数组获取值的开关的指南。基本上,我有一个微调器,其中包含数组中所述的所有项目,所以我想实现一个开关,以便每当我点击一个项目时,它都会触发一个事件,例如,转到另一个活动。

<string-array name="location1">

    <item>string a</item>
    <item>string a</item>
    <item>string b</item>
    <item>string c</item>
    <item>string d</item>

</string-array>

那么,如果我有一个这样的字符串数组,我应该如何实现我的 switch 语句?

【问题讨论】:

  • 您不能在 JDK 7 之前使用 switch on 字符串。我不确定我是否理解您的问题。你能告诉我们更多关于你想做的事情吗? (见stackoverflow.com/questions/338206/…
  • @Romain Guidoux 哦:/ 好吧,基本上我有一个微调器,其中包含数组中所述的所有项目,所以我想实现一个开关,以便每当我点击一个项目时,它都会触发一个事件,例如,去另一个活动。

标签: android switch-statement arrays


【解决方案1】:

如果数组是:

<string-array name="cars_array">
    <item>Audi</item>
    <item>Ferrari</item>
</string-array>

您可以像这样访问它们:

Resources res = getResources();
String[] cars = res.getStringArray(R.array.cars_array);

然后你可以单独访问它们作为汽车[0]、汽车[1]等

如果您想将相同的字符串资源作为数组的一部分并单独访问,那么您可以这样做:

<string name="audi">Audi</string>
<string name="ferrari">Ferrari</string>

<string-array name="cars_array">
    <item>@string/audi</item>
    <item>@string/ferrari</item>
</string-array>

然后你可以简单地说“@string/audi”来单独获取它,也可以使用数组名“@string/cars”来使用整个字符串数组。

【讨论】:

    【解决方案2】:

    我认为 Android 开发者网站上的这个资源可能会对你有所帮助:String Resources

    它会给你类似的东西:

    Resources res = getResources();
    String[] strArray = res.getStringArray(R.array.location1);
    

    【讨论】:

    • Array 在 Java 中甚至不是集合类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-26
    • 2012-10-24
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2016-12-12
    相关资源
    最近更新 更多