Creating hashmap/map from XML resources

后端 未结 6 1383
礼貌的吻别
礼貌的吻别 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:41

    I think the safest and cleanest approach hasn't been posted yet, so here's my $0.02:

    How about creating an enum type in the code that references the string resource id for its display value:

    public enum Country {
       FRA(R.string.france),
       BEL(R.string.belgium),
       SWE(R.string.sweden),
       ...;
    
       @StringRes public int stringResId;
    
       Country(@StringRes id stringResId) {
           this.stringResId = stringResId;
       }
    } 
    

    Then in strings.xml:

    France
    ...
    

    And when you receive an item from the web service:

    Country country = Country.valueOf(countryCodeFromServer);
    context.getResources().getString(country.stringResId);
    

    Build time checks will ensure that each country has a resource for each locale, which you won't have if you maintain the list as an array resource.

提交回复
热议问题