Iga*_*gal 9 audio android android-alertdialog
我有一个带2个按钮的AlertDialog.我希望他们在点击时播放我的自定义声音.所以我在每个按钮上都有这个代码:
SoundUtility.getInstance(Add_Edit_Note.this).playPositive();
Run Code Online (Sandbox Code Playgroud)
SoundUtility是我写的用来播放自定义声音的类.这是问题所在:它确实播放我的自定义声音,但它同时也播放系统声音效果,所以我有两个声音在同一时间播放.我可以通过重写Button来在常规按钮上禁用它:
public class AppButton extends Button {
public AppButton(Context context, AttributeSet attrs) {
super(context, attrs);
// Disable sound effect
this.setSoundEffectsEnabled(false);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的XML文件中:
<com.my.app.AppButton
... />
Run Code Online (Sandbox Code Playgroud)
但我找不到在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();
}
Run Code Online (Sandbox Code Playgroud)
}
编辑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
Run Code Online (Sandbox Code Playgroud)
试试这个
Button btn = dialog.getButton(Dialog.BUTTON_POSITIVE);
btn.setSoundEffectsEnabled(false);
Run Code Online (Sandbox Code Playgroud)
呼叫setSoundEffectsEnabled您拥有的所有按钮
编辑:
代替
builder.create().show();
Run Code Online (Sandbox Code Playgroud)
使用
AlertDialog dialog = builder.create();
dialog.show();
Button btn = dialog.getButton(Dialog.BUTTON_POSITIVE);
btn.setSoundEffectsEnabled(false);
Button btn2 = dialog.getButton(Dialog.BUTTON_NEGATIVE);
btn2.setSoundEffectsEnabled(false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2373 次 |
| 最近记录: |