gpt4 book ai didi

android - 如何禁用AlertDialog 的系统音效?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:35:04 24 4
gpt4 key购买 nike

我有一个带有 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

最佳答案

试试这个

Button btn = dialog.getButton(Dialog.BUTTON_POSITIVE); 
btn.setSoundEffectsEnabled(false);

为您拥有的所有按钮调用setSoundEffectsEnabled

编辑:

代替

 builder.create().show();

使用

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);

关于android - 如何禁用AlertDialog 的系统音效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13952495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com