如何在安卓中动态生成原始资源标识符?

14

我正在开发一款移动图书馆应用。我有3-4个存储在raw文件夹中的数据库文件,包含书籍信息。如果我知道书名,那么我首先将该文件复制到/databases/book_name.db,然后根据需要访问它们。我使用

InputStream fileInputStream = getResources().openRawResource(R.raw.book_name);

用于访问这些文件。

现在,我想传递书名,然后使用字符串book_name动态生成资源标识符R.raw.book_name。 我是否有办法生成此标识符?

3个回答

24

使用Resources.getIdentifier()方法:

int resId = getResources().getIdentifier("raw/book_name", null, this.getPackageName());

如果你的代码不在活动(Activity)或应用(Application)中,你需要先获取上下文(Context)。

Context context = getContext(); // or getBaseContext(), or getApplicationContext()
int resId = context.getResources().getIdentifier("raw/book_name", null, context.getPackageName());

11
如果您有一个带扩展名的文件,比如:raw/list_users.json,那么在使用getResources().getIdentifier("list_users", "raw", "<应用程序包类>")时不需要包含扩展名.json,这个技巧很简单。请注意保持翻译后的意思与原文一致,同时尽可能使其更加通俗易懂。 - divix

5
您可以使用我在这里提供的答案:Android: Accessing string.xml using variable name 尝试使用以下代码:
int identifier = getResources().getIdentifier(bookname, "raw", "<application package class>");

编辑:这个太原始了。


1

基于Sergey的回答。

我在CursorAdapter中使用这个来DRY代码,最终可行的版本是:

String attribute   = "company_name";
String packageName = view.getContext().getPackageName();

int resourceId = view.getResources().getIdentifier(attribute, null, packageName);

实际上,这个问题给我带来了麻烦,所以我切换到以下内容,这似乎更加稳定:

int resourceId = R.id.class.getField(attribute).getInt(null);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接