如何动态地生成机器人的原始资源标识符?标识符、机器人、原始、动态

2023-09-08 09:44:56 作者:可她人间难寻

我的工作流动图书馆应用程序。我有存储在原文件夹书3-4分贝文件。如果我知道这本书的名字,那么我先将该文件复制到/databases/book_name.db,然后根据需要访问它们。我用

I am working on a mobile library app. I have a 3-4 db files of books stored in raw folder. If I know the name of the book then I first copy this file to /databases/book_name.db and then access them as required. I use

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

有关访问这些文件。

现在,我想通过这本书的名字,然后使用字符串BOOK_NAME动态生成资源标识符R.raw.book_name。有没有办法通过它我可以生成此标识?

Now, I want to pass the book name and then dynamically generate the resource identifier R.raw.book_name using the string book_name. Is there a way by which I can generate this identifier?

推荐答案

使用Resources.getIdentifier()方法:

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

如果您的code不活动或应用程序,您需要首先获取上下文。

If your code not in activity or application, you need to get Context first.

Context context = getContext(); // or getBaseContext(), or getApplicationContext()
int resId = getResources().getIdentifier("raw/book_name", null, context.getPackageName());
 
精彩推荐
图片推荐