簡體   English   中英

Android:如何按資源ID檢索文件名和資源擴展名

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

我有以下內容:

getResources().getResourceEntryName(resourceId);

問題是,它只檢索沒有擴展名的文件名。

例如,如果我有以下res / drawable / pic.jpg,那么

getResources().getResourceEntryName(resourceId);

正在返回值“pic”。 擴展名.jpg缺失。

要獲得“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

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

你可以這樣做

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

簡答:你做不到。

另一種方法是將圖形放在assets文件夾中。 然后,您可以直接訪問文件,而無需您的應用程序需要任何權限。

例如,您可以在“活動”中執行此操作:

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

我希望這會實現你的想法。


更新 :似乎確實有可能,請參閱Aleksandar Stojiljkovic的回答

這應該是最好的解決方案:

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

resname =“pic.jpg”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM