简体   繁体   English

Android:如何按资源ID检索文件名和资源扩展名

[英]Android: How to retrieve file name and extension of a resource by resource ID

I have the following: 我有以下内容:

getResources().getResourceEntryName(resourceId);

The problem is, that it retrieves only the file name without the extension. 问题是,它只检索没有扩展名的文件名。

For example, if I have the following res/drawable/pic.jpg, the 例如,如果我有以下res / drawable / pic.jpg,那么

getResources().getResourceEntryName(resourceId);

is returning the value "pic". 正在返回值“pic”。 The extension .jpg is missing. 扩展名.jpg缺失。

To get "res/drawable/pic.jpg" you could use this: 要获得“res / drawable / pic.jpg”,你可以使用这个:

    TypedValue value = new TypedValue();
    getResources().getValue(resourceId, value, true);
    // check value.string if not null - it is not null for drawables...

    Log.d(TAG, "Resource filename:" + value.string.toString());
    // ^^ This would print res/drawable/pic.jpg

Source: android/frameworks/base/core/java/android/content/res/Resources.java 来源:android / frameworks / base / core / java / android / content / res / Resources.java

You can do so 你可以这样做

    Field[] fields = R.raw.class.getFields();
    for (int count = 0; count < fields.length; count++) {

        // Use that if you just need the file name
        String filename = fields[count].getName();
        Log.i("filename", filename);
        int rawId = getResources().getIdentifier(filename, "raw", getPackageName());
        TypedValue value = new TypedValue();
        getResources().getValue(rawId, value, true);
        String[] s = value.string.toString().split("/");
        Log.i("filename", s[s.length - 1]);
    }

Short answer: You can't. 简答:你做不到。

Another way to do this, would be to put your graphics inside the assets folder. 另一种方法是将图形放在assets文件夹中。 Then you can access the Files directly, without your App needing any permission. 然后,您可以直接访问文件,而无需您的应用程序需要任何权限。

You can, for example, do so in your Activity: 例如,您可以在“活动”中执行此操作:

AssetManager am = this.getApplicationContext().getAssets()
InputStream is = am.open(foldername+"/"+filename)
Bitmap myNewImage = BitmapFactory.decodeStream(is);

I hope that this will accomplish what you had in mind. 我希望这会实现你的想法。


UPDATE : it seems it is indeed possible, see Aleksandar Stojiljkovic's answer instead. 更新 :似乎确实有可能,请参阅Aleksandar Stojiljkovic的回答

This should be the best solution: 这应该是最好的解决方案:

 TypedValue value = new TypedValue();
    getResources().getValue(resourceId, value, true); 
String resname = value.string.toString().substring(13, value.string.toString().length());

resname = "pic.jpg" resname =“pic.jpg”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM