我正在尝试制作一个音板,这样当您按下具有特定 android:id 的按钮时,它将播放同名的 .ogg 文件。我已完成布局设置,只需要引用 XML id 方面的帮助。
例如,如果我有这个特定的按钮设置
<Button
android:id="@+id/file022"
android:layout_weight="1"
android:layout_margin="1dp"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:text="Sample Text"
android:textColor="#000000"
android:textStyle="normal"
android:onClick="playSound"
android:background="#B3EDEDED"/>
我可以使用下面的代码来播放相应的声音来播放file022.ogg
(v.getId()==R.id.button14){
MediaPlayer mpSound = MediaPlayer.create(this, R.raw.file022);
mpSound.start();
我需要更改什么才能避免对“R.raw.file001”、“R.raw.file002”进行硬编码 case 语句,而是动态引用 XML 中设置的 ID?
最佳答案
您应该使用 tag
属性来执行此操作,因为检索 ID 的字段名称需要反射。
<Button
...
android:tag="file022"
... />
然后,在代码中,您只需检索标记,并获取该名称的原始资源标识符。
String tag = (String) v.getTag();
int resId = getResources().getIdentifier(tag, "raw", getPackageName());
MediaPlayer mpSound = MediaPlayer.create(this, resId);
mpSound.start();
关于java - 如何动态引用 XML id 来播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27396045/