2011-06-03 119 views
9

我工作的一个移动图书馆的应用。我有一个3-4分贝的文件存储在原始文件夹中。如果我知道这本书的名字,然后我第一个将此文件复制到/databases/book_name.db,然后根据需要访问它们。我用如何在android中动态生成原始资源标识符?

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

访问这些文件。

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

回答

17

使用Resources.getIdentifier()方法:

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

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

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

只是一个提示,如果你有扩展名的文件,例如:'生/ list_users.json'然后不包括扩展名'.json',简单:'getResources()则getIdentifier(”。 list_users“,”raw“,”“)'做一个窍门。 – divix 2016-02-28 14:22:01

+0

@sergeyGlotov感谢这个美丽的答案+1 – 2017-04-22 11:08:51

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