gpt4 book ai didi

Android Dialog,按下按钮时保持对话框打开

转载 作者:IT老高 更新时间:2023-10-28 13:20:41 27 4
gpt4 key购买 nike

我想在按下按钮时保持对话框打开。目前它正在关闭。

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Are you sure you want to exit?")

.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();

最佳答案

是的,你可以。你基本上需要:

  1. 使用 DialogBu​​ilder
  2. 创建对话框
  3. show() 对话框
  4. 在显示的对话框中找到按钮并覆盖它们的 onClickListener

所以,创建一个监听器类:

class CustomListener implements View.OnClickListener {
private final Dialog dialog;

public CustomListener(Dialog dialog) {
this.dialog = dialog;
}

@Override
public void onClick(View v) {

// Do whatever you want here

// If you want to close the dialog, uncomment the line below
//dialog.dismiss();
}
}

然后在显示对话框时使用:

AlertDialog dialog = dialogBuilder.create();
dialog.show();
Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));

请记住,您需要显示对话框,否则将无法找到该按钮。此外,请务必将 DialogInterface.BUTTON_POSITIVE 更改为您用于添加按钮的任何值。另请注意,在 DialogBu​​ilder 中添加按钮时,您需要提供 onClickListeners - 但是,您不能在其中添加自定义监听器 - 如果您在调用 show() 后不要覆盖监听器。

关于Android Dialog,按下按钮时保持对话框打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6142308/

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