gpt4 book ai didi

java - 按下警报对话框按钮始终返回 0 值

转载 作者:行者123 更新时间:2023-12-01 19:46:49 25 4
gpt4 key购买 nike

所以,我想在弹出警报对话框时检测用户按下的按钮。这是我的代码。

public class AlertUtils {

private int BTN_PRESSED;

private AlertDialog.Builder builder;

public AlertUtils(Context context){
builder = new AlertDialog.Builder(context);
}

public int ShowAlertWithTwoButtons(String Title,String Message,String PositiveButtonText,
String NegativeButtonText){
builder.setTitle(Title);
builder.setMessage(Message);

builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
BTN_PRESSED = i;
}
});

builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
BTN_PRESSED = i;
dialogInterface.dismiss();
}
});

builder.show();
return BTN_PRESSED;
}
}

通过调用ShowAlertWithTwoButtons方法,返回int值来检测按下的正向或负向按钮。我的问题是,当我从警报对话框中选择时,它给了我默认 0 值,当我再次打开警报对话框时,它返回正确的值。

最佳答案

按这个方法试试。像这样创建AlertUtils 类。

public class AlertUtils {
private AlertDialog.Builder builder;
private AlertDialogListener alertDialogListener;

// Interface to send back the response of click
interface AlertDialogListener {
void onClick(int a);
}

public AlertUtils(Context context, AlertDialogListener alertDialogListener) {
builder = new AlertDialog.Builder(context);
this.alertDialogListener = alertDialogListener;
}

public void ShowAlertWithTwoButtons(String Title, String Message, String PositiveButtonText,
String NegativeButtonText) {
builder.setTitle(Title);
builder.setMessage(Message);
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// if you want to pass the actual value of i,then pass the i in onClick or if you want 1 on
// positive button click then pass 1 here.
alertDialogListener.onClick(1);
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// if you want to pass the actual value of i, then pass the i in onClick or if you want 1 on
// negative button click then pass 0 here.
alertDialogListener.onClick(0);
dialogInterface.dismiss();
}
});
builder.show();
}

}

在需要的地方以这种方式调用对话框。

  AlertUtils alertUtils = new AlertUtils(getContext(), new AlertUtils.AlertDialogListener() {
@Override
public void onClick(int a) {
if (a == 1) {
// Do your work on Positive button click
} else {
// Do your work on Negative button click
}
}
});
alertUtils.ShowAlertWithTwoButtons("Alert Dialog", "Alert Dialog Description ", "Positive", "Negative");

关于java - 按下警报对话框按钮始终返回 0 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52925790/

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