2 つのボタンを持つ AlertDialog があります。クリックしたときにカスタム サウンドを再生するようにします。だから私はすべてのボタンにこのコードを持っています:
SoundUtility.getInstance(Add_Edit_Note.this).playPositive();
SoundUtility は、カスタム サウンドを再生するために作成したクラスです。ここに問題があります。カスタム サウンドは再生されますが、同時にシステム サウンド エフェクトも再生されるため、同時に 2 つのサウンドが再生されます。ボタンを書き換えることで、通常のボタンで無効にすることができました。
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.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