使用键和 getStringArray (Android) 从资源 xml 文件中检索字符串值

我试图从数组列表中调出特定字符串,而不是运行具有许多单独字符串值的非常大的 switch case。我在xml中有数组列表


<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string-array name="type_items">

        <item name="kitchen_0">spoon</item>

        <item name="kitchen_1">fork</item>

        <item name="bathroom_0">toothbrush</item>

        <item name="bathroom_1">hair brush</item>

    </string-array>

</resources>

在代码中,用户将做出 2 个选择。一个用于房间,另一个用于物品。然后程序将生成项目结果作为字符串输出。


public String result(int room, int item)

{

    String roomID = getResources().getStringArray(R.array.roomlist)[room] + "_" +

                    String.valueOf(item);


    return //needs to return "toothbrush" if roomID is bathroom_0

}

现在我试图从数组列表中返回与该组合关联的值,在四处搜索之后我找不到答案。也许答案是我做错了。任何帮助表示赞赏。


慕雪6442864
浏览 538回答 1
1回答

慕丝7291255

您在使用 Android API 吗?似乎这getStringArray并不意味着使用name属性。它只返回一个包含项目文本值的数组。所以在这里,如果你想检索第 i 个 at 类型的项目,你可以这样重新设计你的资源文件:<?xml version="1.0" encoding="utf-8"?><resources>&nbsp; &nbsp; <string-array name="kitchen">&nbsp; &nbsp; &nbsp; &nbsp; <item>spoon</item>&nbsp; &nbsp; &nbsp; &nbsp; <item>fork</item>&nbsp; &nbsp; </string-array>&nbsp; &nbsp; <string-array name="bathroom">&nbsp; &nbsp; &nbsp; &nbsp; <item>toothbrush</item>&nbsp; &nbsp; &nbsp; &nbsp; <item>hair brush</item>&nbsp; &nbsp; </string-array></resources>并以这种方式编辑您的课程:public final static int KITCHEN_ROOM = R.array.kitchen;public final static int BATHROOM_ROOM = R.array.bathroom;public String result(int room, int i){&nbsp; &nbsp; String[] roomItems =&nbsp; roomID = getResources().getStringArray(room);&nbsp; &nbsp; // [room] + "_" + String.valueOf(item);&nbsp; &nbsp; if (rooms_items.length > i) return roomItems[i];&nbsp; &nbsp; // Here, you can throw an exception or return null;&nbsp; &nbsp; return null;}电话是:System.out.println(result(BATHROOM_ROOM,1)); // "hair brush"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java