简体   繁体   English

如何通过id获取原始资源文件名?

[英]How to get raw resource file name by id?

我在 res/raw 中有 .ogg 文件,我已经实现了将文件保存到 sdcard 的功能,我想从原始文件设置文件名。

使用Resources.getResourceName(id)获取package:type/entryname ,或Resources.getResourceEntryName(id)获取条目名称(文件名)。

If you're looking for the name from a resource ID, you can use Resources.getResourceName() .如果您要从资源 ID 中查找名称,则可以使用Resources.getResourceName() You can get the Resources object using Context.getResources() .您可以使用Context.getResources()获取 Resources 对象。

Personally, I'd rather store an array of strings in your strings.xml and map that to the resource IDs, but it depends on what you're really trying to accomplish.就我个人而言,我更愿意在您的 strings.xml 中存储一个字符串数组并将其映射到资源 ID,但这取决于您真正想要实现的目标。

This is a very old question, but in case others are trying to do the same thing, this worked for getting the filename:这是一个非常古老的问题,但如果其他人试图做同样的事情,这可以用于获取文件名:

Resources myResources = context.getResources();

String myFileName = myResources.getString((int)R.raw.myFile);

For some reason, even though R.raw.myFile is of the type: "final int" and Resources.getString() takes parameter "int id",出于某种原因,即使R.raw.myFile的类型为:“final int”并且Resources.getString()采用参数“int id”,

if you don't cast R.raw.myFile to int, Lint will flag the line with the error "Expected resource of type string"如果您不将R.raw.myFile为 int,Lint 将标记该行并显示错误“预期的字符串类型资源”

Although looking through the documentation, there doesn't seem to be an overloaded version of Resources.getString() that takes a string parameter.尽管查看了文档,但似乎没有采用字符串参数的Resources.getString()的重载版本。

I am on Android Studio v3.6.3, supporting a minimum SDK of 21.我使用的是 Android Studio v3.6.3,支持最低 SDK 为 21。

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

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