Android从变量中获取R.raw

Dah*_*vos 5 android

我的应用程序上的原始文件夹中有一些声音.有时我需要播放声音,但我不知道究竟是哪个.

示例:

String actualSound ="hit"

playSound(mediaPlayer,R.Raw.actualSound));

我当然想玩R.raw.hit,但我不知道怎么做.

谢谢.

Xio*_*ion 14

您可以使用您的原始资源获取原始资源的数字ID,Resources.getIdentifier()然后在您的播放功能中使用它:

Resources res = context.getResources();
int soundId = res.getIdentifier(actualSound, "raw", context.getPackageName());
playSound(mediaPlayer, soundId);
Run Code Online (Sandbox Code Playgroud)

请注意,通常,您不应该这样做.通过数字标识符(即R- 限定常量)访问资源更有效.如果您每次想要在游戏中播放声音时都要执行上述操作,这一点尤为重要.最好使用声音名称(或更好的:枚举值)到资源标识符甚至预加载的声音样本的映射.