Creating hashmap/map from XML resources

后端 未结 6 1397
礼貌的吻别
礼貌的吻别 2020-12-02 09:56

I\'m making an application where a web service fetches (amongst other) a bunch of codes from a webservice (I.e BEL, FRA, SWE). During runtime I want to translate these codes

6条回答
  •  天涯浪人
    2020-12-02 10:35

    I've found Vladimir's answer quite compelling so I implemented his first suggestion:

    public SparseArray parseStringArray(int stringArrayResourceId) {
        String[] stringArray = getResources().getStringArray(stringArrayResourceId);
        SparseArray outputArray = new SparseArray(stringArray.length);
        for (String entry : stringArray) {
            String[] splitResult = entry.split("\\|", 2);
            outputArray.put(Integer.valueOf(splitResult[0]), splitResult[1]);
        }
        return outputArray;
    }
    

    using it is straight forward. In your strings.xml you have a string-array like so:

    
        0|Item 1
        1|Item 4
        2|Item 3
        3|Item 42
        4|Item 17
    
    

    and in your implementation:

    SparseArray myStringArray = parseStringArray(R.array.my_string_array);
    

提交回复
热议问题