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

coo*_*max 13 android

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

InputStream fileInputStream = getResources().openRawResource(R.raw.book_name);
Run Code Online (Sandbox Code Playgroud)

用于访问这些文件.

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

Ser*_*tov 22

使用Resources.getIdentifier()方法:

int resId = getResources().getIdentifier("raw/book_name", null, this.getPackageName());
Run Code Online (Sandbox Code Playgroud)

如果您的代码不在活动或应用程序中,则需要先获取Context.

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

  • 只是一个提示,如果你有一个带扩展名的文件,例如:`raw/list_users.json`则不包含扩展名`.json`,simple:`getResources().getIdentifier("list_users","raw"," <application package class>")`做一个技巧. (7认同)

Fem*_*emi 5

你可以使用我在这里给出的答案:Android:使用变量名访问string.xml

尝试:

int identifier = getResources().getIdentifier(bookname, "raw", "<application package class>");
Run Code Online (Sandbox Code Playgroud)

编辑:嗯,它的原始.