Android从特殊文件获取字符串资源列表 [英] Android get list of string resources from special file

查看:319
本文介绍了Android从特殊文件获取字符串资源列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有 my_string.xml 文件,其中包含字符串:

For example, i have my_string.xml file with strings:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="my_string">My string</string>
    <string name="another_string">Another string</string>
    {...}
</resources>

是否可以通过编程方式将此字符串显示在列表/哈希图中?是的,我知道我可以使用它按名称或类似

Is it possible to get this strings to list/hashmap programmatically? Yeh, i know that i can take it by name or something like this. But i need to get it dynamically programmatically, for example, to HashMap<String, String>

还是所有字符串资源在构建后都将合并在一起,并且无法将其分开?

Or all string resources will merge together after building and it's not possible to separate it?

推荐答案

将文件放在raw文件夹中.然后,您必须打开文件

Put the file in the raw folder. Then you have to open the file

InputStream in = getResources().openRawResource(R.raw.yourfile);

并手动解析内容,例如将列表另存为xml或json并进行解析,然后构建所需的HashMap或您喜欢的任何内容.请记住,这可能是一项阻塞操作,不应在主UI线程上运行,以异步方式运行它,但这取决于您尝试解析的文件的长度,但通常应在异步线程中运行该文件

and parse the content manually, for instance save the list as xml or json and parse it and build your desired HashMap or whatever you like. Keep in mind that this may be a blocking operation and should not run on the main UI thread, run it async, but it depends on the length of the file you try to parse, but in general you should run that in an async thread

----更新 您可以执行以下操作:

---- Update You could do something like this:

int stringRes[] = {R.string.my_string, R.string.another_string}
List<String> myStrings = new ArrayList<String>();
for (int id : stringRes){

   String str = getResources().getString(id);
   // TODO do some if check if you want to keep that string or whatever you want to ...
   myStrings.add(str);
}

您可以将它们存储到HashMap中(但是getResources().getString()的行为已经像HashMap一样)或List

you could store them into a HashMap(but getResources().getString() acts already like a HashMap ) or List

这篇关于Android从特殊文件获取字符串资源列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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