gpt4 book ai didi

带有 DialogFragment : don't close the dialog even if OK is clicked 的 Android AlertDialog

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

我有一个带有自定义布局的 AlertDialog(只是一个 EditText),我想在单击“确定”按钮时验证数据。如果验证失败,我不想关闭对话框。

我正在使用对话框的默认按钮(正面和负面)。如果我使用“setPositiveButton(”), new DialogInterface.OnClickListener() ...”对话框总是关闭的。我看过几个帖子,他们说应该覆盖 onClick Listener,但我无法让它工作. 这是我找到的代码:

Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));

因为它说它应该在显示对话框之后完成,所以我将这段代码放在我的 Activity 中,而不是我的 DialogFragment 中,但是如果我使用 mDialogFragment.getDialog() 它总是返回 null。

这是我的对话 fragment 的一部分:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

builder.setTitle(R.string.new);

LayoutInflater inflater = getActivity().getLayoutInflater();
dialogView = inflater.inflate(R.layout.edit_license, null);

builder.setView(dialogView)

// Add action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {

}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyDialogFragment.this.getDialog().cancel();
}
});

return builder.create();

}

在我的 Activity 中,我执行以下操作:

DialogFragment dialog = new MyDialogFragment(true, null);
dialog.show(getSupportFragmentManager(), "EditLicenseDialogFragment");

AlertDialog alertDialog = (AlertDialog)dialog.getDialog();
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
btnPositive.setOnClickListener(new CustomListener(alertDialog));

...

class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
@Override
public void onClick(View v) {
...
}
}

就像我说的,(AlertDialog)dialog.getDialog();总是返回空值。这是为什么?如果验证不正确,如何避免关闭对话框?

谢谢!

最佳答案

这个解决方案适合我。对话框在 onResume 中已经可见,因此这是访问按钮和替换监听器的好地方。

public class XYZFragment extends DialogFragment {
...

@Override
public void onResume() {
super.onResume();

AlertDialog dialog = (AlertDialog)getDialog();

Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View onClick) {
...
}
});
}
}

关于带有 DialogFragment : don't close the dialog even if OK is clicked 的 Android AlertDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14830962/

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