安卓:使用包含HashMap和字符串 [英] Android:using hashmaps and strings

查看:116
本文介绍了安卓:使用包含HashMap和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚开始涉足Android版,并已告知字符串不应该是很难coded到Java,但投入的字符串资源文件夹中。

just started dabbling in Android and have been told that Strings shouldnt be hard coded into Java but put into the string resource folder.

我有现有的code其中一个HashMap中的键和值都是strings.How我会去把字符串转换为XML,并把他们从java的部分完全?

I have existing code where in a hashmap the key and value are both strings.How would i go about putting the strings into xml and taking them out of the java part completely?

如果我只是在字符串资源文件夹中创建一个字符串,像这样

Should I just create a string in the string resource folder like so

<string name="hello">Hello.world</string>

与你好是关键和现实存在的价值,然后只用解析字符串。作为分隔符?

with hello being the key and world being the value and then just parse the string using the . as a delimiter?

Hopefuly我已经正确解释自己

Hopefuly I've explained myself correctly

推荐答案

有,你可以在res文件夹中定义许多其他资源类型。你可以看到,可用的这里和的此处。你的目的,一种方法可以定义一个数组在res /价值/ arrays.xml:

There are many other resource types that you can define in the res folder. You can see the available ones here and here. For your purpose, One approach could be defining an array in res/values/arrays.xml:

<resources> 
    <string-array name="hashmap"> 
        <item>key1</item> 
        <item>value1</item> 
        <item>key2</item> 
        <item>value2</item> 
        <item>key3</item> 
        <item>value3</item> 
    </string-array> 
</resources> 

和在code:

Resources res = this.getResources();
String[] hashmapData = res.getStringArray(R.array.hashmap);
HashMap<String, String> map = new HashMap<String, String>(); 
for(int i=0; i<hashmapData.length; i=i+2) { 
    map.put(hashmapData[i], hashmapData[i+1]);         
} 

这篇关于安卓:使用包含HashMap和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆