我有一个带有 2 个按钮的 AlertDialog。我希望他们在点击时播放我的自定义声音。所以我在每个按钮上都有这个代码:
SoundUtility.getInstance(Add_Edit_Note.this).playPositive();
SoundUtility 是我编写的用于播放自定义声音的类。问题是:它确实播放了我的自定义声音,但同时它也播放了系统音效,所以我同时播放了两个声音。我可以通过重写按钮在常规按钮上禁用它:
public class AppButton extends Button {
public AppButton(Context context, AttributeSet attrs) {
super(context, attrs);
// Disable sound effect
this.setSoundEffectsEnabled(false);
}
}
然后在我的 XML 文件中:
<com.my.app.AppButton
... />
但我找不到在 AlertDialog 按钮上禁用这些系统音效的方法。有什么建议么?
编辑
根据要求,这是 SoundUtility 代码:
public class SoundUtility {
private static SoundUtility soundInstance;
private MediaPlayer mpPositive;
private MediaPlayer mpNegative;
public static SoundUtility getInstance(Context context){
if(soundInstance==null)
{
soundInstance = new SoundUtility(context);
}
return soundInstance;
}
private SoundUtility (Context context)
{
mpPositive = MediaPlayer.create(context, R.raw.click_positive);
mpNegative = MediaPlayer.create(context, R.raw.click_negative);
}
// Playing positive sound
public void playPositive() {
mpPositive.start();
}
// Playing negative sound
public void playNegative() {
mpNegative.start();
}
// Releasing MediaPlayer
public void releaseMediaPlayer() {
mpPositive.release();
mpNegative.release();
}
}
编辑 2
我的 AlertDialog 的代码:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to cancel?")
.setCancelable(false) // The dialog is modal, a user must provide an answer
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
// If the answer is Yes
public void onClick(DialogInterface dialog, int id) {
...
setResult(RESULT_CANCELED); // Setting result as cancelled and returning it to main activity
SoundUtility.getInstance(Add_Edit_Note.this).playPositive(); // Play positive sound
Add_Edit_Note.this.finish(); // Closing current activity
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
// If the answer is No
public void onClick(DialogInterface dialog, int id) {
SoundUtility.getInstance(Add_Edit_Note.this).playNegative(); // Play negative sound
dialog.cancel(); // Closing the confirmation dialog
}
});
builder.create().show(); // Present the dialog to the user