【问题标题】:Android - getting the R.raw.value of a file based on filename?Android - 根据文件名获取文件的 R.raw.value?
【发布时间】:2012-08-04 01:35:03
【问题描述】:

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

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

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

String param = "book1tabs";

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

有什么办法吗?

谢谢

【问题讨论】:

    标签: java android string file


    【解决方案1】:

    你可以这样做

    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

    【讨论】:

    • 哇,那句台词真是拗口……但是,如果它成功了,那就太棒了。将对其进行测试。
    【解决方案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(假设存在这样的资源)。对于 R.drawable 中的类传递和字符串,无论它基于 xml 的 ID 名称是什么。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 2012-10-30
      • 2017-07-18
      • 1970-01-01
      相关资源
      最近更新 更多