3

我在 res/raw 文件夹中有一个名为“book1tabs.txt”的文件,但总的来说我不知道​​它叫什么。然后我必须执行以下操作:

InputStream in = this.mCtx.getResources().openRawResource(R.raw.book1tabs);

但我想使用一个字符串变量,比如

String param = "book1tabs";

并且能够打开相同的输入流。

有没有办法做到这一点?

谢谢

4

2 回答 2

7

你可以做这样的事情

String param = "book1tabs";

InputStream in = this.mCtx.getResources().openRawResource(mCtx.getResources().getIdentifier(param,"raw", mCtx.getPackageName()));

getIdentifier()将返回R.java您传递的特定参数的 id。

它的具体作用如下

  • 映射包名称
  • 导航到您提供的 typeDef
  • 查找您在 typeDef 中提供的资源名称

更多信息http://developer.android.com/reference/android/content/res/Resources.html

于 2012-08-07T04:14:43.540 回答
2

我发现这种方法对于通过字符串名称提取各种资源非常有用......

    @SuppressWarnings("rawtypes")
public static int getResourceId(String name,  Class resType){

    try {
        Class res = null;
        if(resType == R.drawable.class)
            res = R.drawable.class;
        if(resType == R.id.class)
            res = R.id.class;
        if(resType == R.string.class)
            res = R.string.class;
                    if(resType == R.raw.class)
            res = R.raw.class;
        Field field = res.getField(name);
        int retId = field.getInt(null);
        return retId;
    }
    catch (Exception e) {
       // Log.d(TAG, "Failure to get drawable id.", e);
    }
    return 0;
}

这将返回数字 id(假设存在这样的资源)。对于 Class 传入R.drawable和字符串,无论它基于 xml 的 ID 名称是什么。

我总是在我所有的项目中使用这种方法,以便于访问。

于 2012-08-07T04:19:29.950 回答