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

时间:2011-06-03 03:45:47

标签: android

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

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

用于访问这些文件。

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

3 个答案:

答案 0 :(得分:21)

使用Resources.getIdentifier()方法:

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

如果您的代码不在活动或应用程序中,则需要先获取上下文。

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

答案 1 :(得分:5)

您可以使用我在此处给出的答案:Android: Accessing string.xml using variable name

尝试:

int identifier = getResources().getIdentifier(bookname, "raw", "<application package class>");
编辑:嗯,它的原始。

答案 2 :(得分:1)

基于谢尔盖的回答。

我在CursorAdapter中使用它来干掉代码,最终的版本是:

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);