Android Is it possible to define a map in an XML file?

前端 未结 4 829
执念已碎
执念已碎 2020-12-14 08:02

I was trying to define a static hash table that makes use of resources, but I got stonewalled by the impossibility of accessing resources statically.

Then I realized

4条回答
  •  生来不讨喜
    2020-12-14 08:30

    A simpler option would be to use two arrays. This has the benefit of not iterating the xml file again, uses less code and its more straight forward to use arrays of different types.

    
       key1
       key1
    
    
    
       value1
       value2
    
    

    Then your java code would look like this:

    String[] keys = this.getResources().getStringArray(R.array.myvariablename_keys);
    String[] values = this.getResources().getStringArray(R.array.myvariablename_values);
    LinkedHashMap map = new LinkedHashMap();
    for (int i = 0; i < Math.min(keys.length, values.length); ++i) {
       map.put(keys[i], values[i]);
    }
    

提交回复
热议问题